From 051e154c65f1129fbf2f46f615b525554cc5cd38 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Sat, 9 Mar 2024 23:35:00 +0000 Subject: [PATCH] Re-add old blog posts from Astro --- app/config/sculpin_kernel.yml | 2 +- source/_includes/figure.html.twig | 8 + source/_includes/tweet.html.twig | 10 + source/_includes/youtube-video.html.twig | 14 +- source/_layouts/post.html.twig | 16 + .../10-years-working-full-time-drupal-php.md | 29 + source/_posts/2014.md | 84 +++ source/_posts/accessible-bristol-site.md | 30 + ...-taxonomy-term-multiple-nodes-using-sql.md | 79 ++ .../adding-custom-theme-templates-drupal-7.md | 84 +++ .../announcing-the-drupal-vm-generator.md | 104 +++ source/_posts/automating-sculpin-jenkins.md | 192 +++++ .../back-future-gits-diff-apply-commands.md | 72 ++ .../_posts/building-gmail-filters-in-php.md | 102 +++ ...uilding-oliverdavies-uk-1-initial-setup.md | 19 + .../_posts/building-the-new-phpsw-website.md | 37 + ...e-content-type-multiple-nodes-using-sql.md | 42 ++ ...hecking-if-user-logged-drupal-right-way.md | 68 ++ ...kout-specific-revision-svn-command-line.md | 22 + ...file-data-using-entity-metadata-wrapper.md | 38 + .../conditional-email-addresses-webform.md | 29 + .../configuring-the-reroute-email-module.md | 70 ++ ...s-integration-vs-continuous-integration.md | 46 ++ ...eate-better-photo-gallery-drupal-part-1.md | 161 ++++ ...eate-better-photo-gallery-drupal-part-2.md | 58 ++ ...ate-better-photo-gallery-drupal-part-21.md | 64 ++ ...eate-better-photo-gallery-drupal-part-3.md | 49 ++ ...dia-icons-using-cck-views-and-nodequeue.md | 44 ++ ...ckr-photo-gallery-using-feeds-cck-views.md | 71 ++ ...groups-drupal-7-using-field-collections.md | 59 ++ ...reprocessor-using-omega-tools-and-drush.md | 62 ++ ...eshow-multiple-images-using-fancy-slide.md | 50 ++ ...rtual-hosts-mac-os-x-using-virtualhostx.md | 50 ++ .../create-zen-sub-theme-using-drush.md | 40 + .../creating-custom-phpunit-command-ddev.md | 82 ++ ...creating-custom-phpunit-command-docksal.md | 366 +++++++++ ...ing-sites-drupals-domain-module-enabled.md | 52 ++ .../creating-using-custom-tokens-drupal-7.md | 162 ++++ source/_posts/croeso-php-south-wales.md | 82 ++ ...-drupal-commerce-illuminate-collections.md | 140 ++++ .../debugging-php-docker-xdebug-neovim-dap.md | 102 +++ ...y-metadata-wrapper-add-refactor-methods.md | 141 ++++ ...ustom-menu-drupal-7-theme-template-file.md | 27 + ...it-branch-or-tag-names-your-bash-prompt.md | 67 ++ .../display-number-facebook-fans-php.md | 30 + ...and-preprocess-functions-separate-files.md | 93 +++ source/_posts/docker-resources.md | 22 + .../_posts/dont-bootstrap-drupal-use-drush.md | 73 ++ ...ownload-different-versions-drupal-drush.md | 59 ++ source/_posts/drupal-8-5-released.md | 38 + ...-commerce-fixing-error-on-user-checkout.md | 95 +++ source/_posts/drupal-association.md | 37 + ...drupal-automated-testing-workshop-notes.md | 14 + .../drupal-body-classes-tailwind-css.md | 153 ++++ .../_posts/drupal-bristol-testing-workshop.md | 112 +++ source/_posts/drupal-vm-generator-updates.md | 35 + source/_posts/drupalcamp-bristol-2018.md | 46 ++ ...ristol-2019-speakers-sessions-announced.md | 27 + ...ol-early-bird-tickets-sessions-sponsors.md | 68 ++ source/_posts/drupalcamp-london-2014.md | 24 + .../_posts/drupalcamp-london-2019-tickets.md | 39 + .../drupalcamp-london-testing-workshop.mdx | 29 + ...easier-git-repository-cloning-insteadof.md | 82 ++ ...r-sculpin-commands-composer-npm-scripts.md | 78 ++ ...embed-typekit-fonts-your-drupal-website.md | 32 + source/_posts/entityform.md | 62 ++ .../_posts/experimenting-events-drupal-8.md | 81 ++ source/_posts/feature-flags-sculpin.md | 103 +++ ...the-last-commit-that-a-patch-applies-to.md | 49 ++ ...pletest-issues-inside-docker-containers.md | 130 ++++ ...omain-another-using-modrewrite-htaccess.md | 29 + source/_posts/git-format-patch-your-friend.md | 136 ++++ .../_posts/github-actions-phpunit-colours.md | 11 + source/_posts/going-drupalcon.md | 16 + source/_posts/going-full-vim.md | 50 ++ ...how-add-date-popup-calendar-custom-form.md | 44 ++ source/_posts/how-create-apply-patches.md | 50 ++ ...x-vagrant-loading-wrong-virtual-machine.md | 26 + ...-configure-subversion-svn-server-ubuntu.md | 178 +++++ ...ication-subdirectory-another-site-nginx.md | 29 + ...8-phpunit-tests-within-docksal-phpstorm.md | 217 ++++++ ...-variables-your-drupal-settings-docksal.md | 92 +++ .../ignoring-phpcs-sniffs-phpunit-tests.md | 77 ++ source/_posts/imagefield-import-archive.md | 35 + ...ove-jpg-quality-imagecache-and-imageapi.md | 25 + .../include-css-fonts-using-sass-each-loop.md | 67 ++ ...onment-specific-settings-files-pantheon.md | 100 +++ ...environment-configuration-and-overrides.md | 62 ++ .../install-nomensa-media-player-drupal.md | 85 +++ source/_posts/installing-nagios-centos.md | 15 + .../interview-drupal-expert-code-enigma.md | 13 + ...introducing-drupal-distribution-meetups.md | 29 + ...troducing-the-drupal-meetups-twitterbot.md | 29 + .../leaving-nomensa-joining-precedent.md | 32 + .../live-blogging-symfonylive-london-2019.md | 713 ++++++++++++++++++ .../looking-forward-to-drupalcamp-london.md | 66 ++ .../mediacurrent-contrib-half-hour-is-back.md | 67 ++ .../_posts/migrating-drupal-8-introduction.md | 22 + source/_posts/minimum-core-version.md | 96 +++ ...my-first-blog-post-published-for-inviqa.md | 12 + .../my-first-six-months-transport-wales.md | 45 ++ source/_posts/my-new-drupal-modules.md | 24 + source/_posts/my-sublime-text-2-settings.md | 106 +++ .../neovim-database-plugin-vim-dadbod-ui.md | 5 + .../nginx-redirects-query-string-arguments.md | 57 ++ .../_posts/null-users-system-users-drupal.md | 155 ++++ ...en-sublime-text-2-mac-os-x-command-line.md | 23 + ...-tailwind-css-and-ansible-at-cms-philly.md | 23 + ...lides-using-pdfpc-pdf-presenter-console.md | 91 +++ ...isplaying-text-files-within-web-browser.md | 28 + source/_posts/proctor-stevenson.md | 20 + .../proctors-hosting-next-drupal-meetup.md | 15 + .../psr4-autoloading-test-cases-drupal-7.md | 143 ++++ ...es-docker-hub-adr-tools-sculpin-rst2pdf.md | 97 +++ .../_posts/published-my-first-npm-package.md | 117 +++ ...lishing-sculpin-sites-with-github-pages.md | 113 +++ .../queuing-private-messages-drupal-8.md | 84 +++ .../quick-project-switching-phpstorm.md | 67 ++ ...ckest-way-install-sublime-text-2-ubuntu.md | 25 + ...ly-apply-patches-using-git-curl-or-wget.md | 29 + ...es-images-using-imagefieldimport-module.md | 44 ++ ...cquia-dashboard-with-vuejs-tailwind-css.md | 163 ++++ ...default-theme-vuejs-tailwind-css-part-2.md | 313 ++++++++ ...rupals-default-theme-vuejs-tailwind-css.md | 345 +++++++++ .../reflections-speaking-unifieddiff.md | 40 + .../_posts/renaming-gray-grey-tailwind-css.md | 32 + ...uring-my-tailwindjs-configuration-files.md | 236 ++++++ source/_posts/review-adminhover-module.md | 58 ++ source/_posts/review-image-caption-module.md | 40 + source/_posts/review-teleport-module.md | 39 + .../running-drupal-88-symfony-local-server.md | 323 ++++++++ source/_posts/sculpin-twig-resources.md | 51 ++ ...simplifying-drupal-migrations-xautoload.md | 135 ++++ source/_posts/site-upgraded-drupal-7.md | 22 + source/_posts/some-useful-git-aliases.md | 34 + ...me-useful-links-using-simpletest-drupal.md | 19 + .../_posts/south-wales-drupal-user-group.md | 20 + source/_posts/speaking-drupalcon-amsterdam.md | 39 + .../_posts/speaking-drupalcon-europe-2020.md | 17 + .../speaking-remotely-during-covid-19.md | 84 +++ .../splitting-new-drupal-project-from-repo.md | 163 ++++ ...reaming-spabby-gary-hockin-about-drupal.md | 22 + ...al-6s-taxonomy-lists-php-css-and-jquery.md | 75 ++ ...alcon-europe-session-test-driven-drupal.md | 96 +++ ...riven-ansible-role-development-molecule.md | 39 + .../test-driven-drupal-on-gitstore-leanpub.md | 37 + ...en-drupal-presentation-drupalcon-europe.md | 22 + .../testing-tailwind-css-plugins-jest.md | 284 +++++++ source/_posts/thanks.md | 14 + .../turning-drupal-module-into-feature.md | 35 + source/_posts/tweets-drupalcamp-london.md | 69 ++ source/_posts/uis-ive-rebuilt-tailwind-css.md | 22 + ...-features-adding-components-using-drush.md | 74 ++ source/_posts/updating-forked-github-repos.md | 121 +++ .../updating-override-node-options-tests.md | 239 ++++++ .../upgrading-dransible-project-drupal-9.md | 51 ++ ...keys-create-passwordless-ssh-connection.md | 33 + ...essions-search-replace-coda-or-textmate.md | 57 ++ ...e-sass-and-compass-drupal-7-using-sassy.md | 79 ++ source/_posts/useful-drupal-6-modules.md | 57 ++ source/_posts/useful-vagrant-commands.md | 24 + ...ing-feature-flags-in-drupal-development.md | 13 + ...g-imagecache-and-imagecrop-my-portfolio.md | 44 ++ .../using-laravel-collections-drupal.md | 71 ++ ...g-pcss-extension-postcss-webpack-encore.md | 94 +++ ...eloping-locally-stage-file-proxy-module.md | 37 + .../using-tailwind-css-your-drupal-theme.md | 112 +++ .../using-traefik-local-proxy-sculpin.md | 64 ++ source/_posts/using-transition-props-vuejs.md | 13 + source/_posts/weeknotes-2021-06-05.md | 26 + source/_posts/weeknotes-2021-06-12.md | 36 + source/_posts/weeknotes-2021-07-24.md | 44 ++ source/_posts/weeknotes-2021-08-06.md | 32 + source/_posts/what-git-flow.md | 59 ++ .../_posts/writing-article-linux-journal.md | 22 + .../writing-info-file-drupal-7-theme.md | 40 + ...odule-using-test-driven-development-tdd.md | 661 ++++++++++++++++ source/_posts/zenophile.md | 24 + 178 files changed, 13479 insertions(+), 7 deletions(-) create mode 100644 source/_includes/figure.html.twig create mode 100644 source/_includes/tweet.html.twig create mode 100644 source/_layouts/post.html.twig create mode 100644 source/_posts/10-years-working-full-time-drupal-php.md create mode 100644 source/_posts/2014.md create mode 100644 source/_posts/accessible-bristol-site.md create mode 100644 source/_posts/add-taxonomy-term-multiple-nodes-using-sql.md create mode 100644 source/_posts/adding-custom-theme-templates-drupal-7.md create mode 100644 source/_posts/announcing-the-drupal-vm-generator.md create mode 100644 source/_posts/automating-sculpin-jenkins.md create mode 100644 source/_posts/back-future-gits-diff-apply-commands.md create mode 100644 source/_posts/building-gmail-filters-in-php.md create mode 100644 source/_posts/building-oliverdavies-uk-1-initial-setup.md create mode 100644 source/_posts/building-the-new-phpsw-website.md create mode 100644 source/_posts/change-content-type-multiple-nodes-using-sql.md create mode 100644 source/_posts/checking-if-user-logged-drupal-right-way.md create mode 100644 source/_posts/checkout-specific-revision-svn-command-line.md create mode 100644 source/_posts/cleanly-retrieving-user-profile-data-using-entity-metadata-wrapper.md create mode 100644 source/_posts/conditional-email-addresses-webform.md create mode 100644 source/_posts/configuring-the-reroute-email-module.md create mode 100644 source/_posts/continuous-integration-vs-continuous-integration.md create mode 100644 source/_posts/create-better-photo-gallery-drupal-part-1.md create mode 100644 source/_posts/create-better-photo-gallery-drupal-part-2.md create mode 100644 source/_posts/create-better-photo-gallery-drupal-part-21.md create mode 100644 source/_posts/create-better-photo-gallery-drupal-part-3.md create mode 100644 source/_posts/create-block-social-media-icons-using-cck-views-and-nodequeue.md create mode 100644 source/_posts/create-flickr-photo-gallery-using-feeds-cck-views.md create mode 100644 source/_posts/create-multigroups-drupal-7-using-field-collections.md create mode 100644 source/_posts/create-omega-subtheme-less-css-preprocessor-using-omega-tools-and-drush.md create mode 100644 source/_posts/create-slideshow-multiple-images-using-fancy-slide.md create mode 100644 source/_posts/create-virtual-hosts-mac-os-x-using-virtualhostx.md create mode 100644 source/_posts/create-zen-sub-theme-using-drush.md create mode 100644 source/_posts/creating-custom-phpunit-command-ddev.md create mode 100644 source/_posts/creating-custom-phpunit-command-docksal.md create mode 100644 source/_posts/creating-local-and-staging-sites-drupals-domain-module-enabled.md create mode 100644 source/_posts/creating-using-custom-tokens-drupal-7.md create mode 100644 source/_posts/croeso-php-south-wales.md create mode 100644 source/_posts/debugging-drupal-commerce-illuminate-collections.md create mode 100755 source/_posts/debugging-php-docker-xdebug-neovim-dap.md create mode 100644 source/_posts/decorating-entity-metadata-wrapper-add-refactor-methods.md create mode 100644 source/_posts/display-custom-menu-drupal-7-theme-template-file.md create mode 100644 source/_posts/display-git-branch-or-tag-names-your-bash-prompt.md create mode 100644 source/_posts/display-number-facebook-fans-php.md create mode 100644 source/_posts/dividing-drupals-process-and-preprocess-functions-separate-files.md create mode 100644 source/_posts/docker-resources.md create mode 100644 source/_posts/dont-bootstrap-drupal-use-drush.md create mode 100644 source/_posts/download-different-versions-drupal-drush.md create mode 100644 source/_posts/drupal-8-5-released.md create mode 100644 source/_posts/drupal-8-commerce-fixing-error-on-user-checkout.md create mode 100644 source/_posts/drupal-association.md create mode 100644 source/_posts/drupal-automated-testing-workshop-notes.md create mode 100644 source/_posts/drupal-body-classes-tailwind-css.md create mode 100644 source/_posts/drupal-bristol-testing-workshop.md create mode 100644 source/_posts/drupal-vm-generator-updates.md create mode 100644 source/_posts/drupalcamp-bristol-2018.md create mode 100644 source/_posts/drupalcamp-bristol-2019-speakers-sessions-announced.md create mode 100644 source/_posts/drupalcamp-bristol-early-bird-tickets-sessions-sponsors.md create mode 100644 source/_posts/drupalcamp-london-2014.md create mode 100644 source/_posts/drupalcamp-london-2019-tickets.md create mode 100644 source/_posts/drupalcamp-london-testing-workshop.mdx create mode 100644 source/_posts/easier-git-repository-cloning-insteadof.md create mode 100644 source/_posts/easier-sculpin-commands-composer-npm-scripts.md create mode 100644 source/_posts/easily-embed-typekit-fonts-your-drupal-website.md create mode 100644 source/_posts/entityform.md create mode 100644 source/_posts/experimenting-events-drupal-8.md create mode 100644 source/_posts/feature-flags-sculpin.md create mode 100644 source/_posts/finding-the-last-commit-that-a-patch-applies-to.md create mode 100644 source/_posts/fixing-drupal-simpletest-issues-inside-docker-containers.md create mode 100644 source/_posts/forward-one-domain-another-using-modrewrite-htaccess.md create mode 100644 source/_posts/git-format-patch-your-friend.md create mode 100644 source/_posts/github-actions-phpunit-colours.md create mode 100644 source/_posts/going-drupalcon.md create mode 100644 source/_posts/going-full-vim.md create mode 100644 source/_posts/how-add-date-popup-calendar-custom-form.md create mode 100644 source/_posts/how-create-apply-patches.md create mode 100644 source/_posts/how-fix-vagrant-loading-wrong-virtual-machine.md create mode 100644 source/_posts/how-install-configure-subversion-svn-server-ubuntu.md create mode 100644 source/_posts/how-put-your-php-application-subdirectory-another-site-nginx.md create mode 100644 source/_posts/how-run-drupal-8-phpunit-tests-within-docksal-phpstorm.md create mode 100644 source/_posts/how-use-environment-variables-your-drupal-settings-docksal.md create mode 100644 source/_posts/ignoring-phpcs-sniffs-phpunit-tests.md create mode 100644 source/_posts/imagefield-import-archive.md create mode 100644 source/_posts/improve-jpg-quality-imagecache-and-imageapi.md create mode 100644 source/_posts/include-css-fonts-using-sass-each-loop.md create mode 100644 source/_posts/include-environment-specific-settings-files-pantheon.md create mode 100644 source/_posts/include-local-drupal-settings-file-environment-configuration-and-overrides.md create mode 100644 source/_posts/install-nomensa-media-player-drupal.md create mode 100644 source/_posts/installing-nagios-centos.md create mode 100644 source/_posts/interview-drupal-expert-code-enigma.md create mode 100644 source/_posts/introducing-drupal-distribution-meetups.md create mode 100644 source/_posts/introducing-the-drupal-meetups-twitterbot.md create mode 100644 source/_posts/leaving-nomensa-joining-precedent.md create mode 100644 source/_posts/live-blogging-symfonylive-london-2019.md create mode 100644 source/_posts/looking-forward-to-drupalcamp-london.md create mode 100644 source/_posts/mediacurrent-contrib-half-hour-is-back.md create mode 100644 source/_posts/migrating-drupal-8-introduction.md create mode 100644 source/_posts/minimum-core-version.md create mode 100644 source/_posts/my-first-blog-post-published-for-inviqa.md create mode 100644 source/_posts/my-first-six-months-transport-wales.md create mode 100644 source/_posts/my-new-drupal-modules.md create mode 100644 source/_posts/my-sublime-text-2-settings.md create mode 100644 source/_posts/neovim-database-plugin-vim-dadbod-ui.md create mode 100644 source/_posts/nginx-redirects-query-string-arguments.md create mode 100644 source/_posts/null-users-system-users-drupal.md create mode 100644 source/_posts/open-sublime-text-2-mac-os-x-command-line.md create mode 100644 source/_posts/presenting-on-tailwind-css-and-ansible-at-cms-philly.md create mode 100644 source/_posts/presenting-pdf-slides-using-pdfpc-pdf-presenter-console.md create mode 100644 source/_posts/prevent-apache-displaying-text-files-within-web-browser.md create mode 100644 source/_posts/proctor-stevenson.md create mode 100644 source/_posts/proctors-hosting-next-drupal-meetup.md create mode 100644 source/_posts/psr4-autoloading-test-cases-drupal-7.md create mode 100644 source/_posts/published-my-first-docker-images-docker-hub-adr-tools-sculpin-rst2pdf.md create mode 100644 source/_posts/published-my-first-npm-package.md create mode 100644 source/_posts/publishing-sculpin-sites-with-github-pages.md create mode 100644 source/_posts/queuing-private-messages-drupal-8.md create mode 100644 source/_posts/quick-project-switching-phpstorm.md create mode 100644 source/_posts/quickest-way-install-sublime-text-2-ubuntu.md create mode 100644 source/_posts/quickly-apply-patches-using-git-curl-or-wget.md create mode 100644 source/_posts/quickly-import-multiples-images-using-imagefieldimport-module.md create mode 100644 source/_posts/rebuilding-acquia-dashboard-with-vuejs-tailwind-css.md create mode 100644 source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css-part-2.md create mode 100644 source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css.md create mode 100644 source/_posts/reflections-speaking-unifieddiff.md create mode 100644 source/_posts/renaming-gray-grey-tailwind-css.md create mode 100644 source/_posts/restructuring-my-tailwindjs-configuration-files.md create mode 100644 source/_posts/review-adminhover-module.md create mode 100644 source/_posts/review-image-caption-module.md create mode 100644 source/_posts/review-teleport-module.md create mode 100644 source/_posts/running-drupal-88-symfony-local-server.md create mode 100644 source/_posts/sculpin-twig-resources.md create mode 100644 source/_posts/simplifying-drupal-migrations-xautoload.md create mode 100644 source/_posts/site-upgraded-drupal-7.md create mode 100644 source/_posts/some-useful-git-aliases.md create mode 100644 source/_posts/some-useful-links-using-simpletest-drupal.md create mode 100644 source/_posts/south-wales-drupal-user-group.md create mode 100644 source/_posts/speaking-drupalcon-amsterdam.md create mode 100644 source/_posts/speaking-drupalcon-europe-2020.md create mode 100644 source/_posts/speaking-remotely-during-covid-19.md create mode 100644 source/_posts/splitting-new-drupal-project-from-repo.md create mode 100644 source/_posts/streaming-spabby-gary-hockin-about-drupal.md create mode 100644 source/_posts/style-drupal-6s-taxonomy-lists-php-css-and-jquery.md create mode 100644 source/_posts/survey-results-my-drupalcon-europe-session-test-driven-drupal.md create mode 100644 source/_posts/test-driven-ansible-role-development-molecule.md create mode 100644 source/_posts/test-driven-drupal-on-gitstore-leanpub.md create mode 100644 source/_posts/test-driven-drupal-presentation-drupalcon-europe.md create mode 100644 source/_posts/testing-tailwind-css-plugins-jest.md create mode 100644 source/_posts/thanks.md create mode 100644 source/_posts/turning-drupal-module-into-feature.md create mode 100644 source/_posts/tweets-drupalcamp-london.md create mode 100644 source/_posts/uis-ive-rebuilt-tailwind-css.md create mode 100644 source/_posts/updating-features-adding-components-using-drush.md create mode 100644 source/_posts/updating-forked-github-repos.md create mode 100644 source/_posts/updating-override-node-options-tests.md create mode 100644 source/_posts/upgrading-dransible-project-drupal-9.md create mode 100644 source/_posts/use-authorized-keys-create-passwordless-ssh-connection.md create mode 100644 source/_posts/use-regular-expressions-search-replace-coda-or-textmate.md create mode 100644 source/_posts/use-sass-and-compass-drupal-7-using-sassy.md create mode 100644 source/_posts/useful-drupal-6-modules.md create mode 100644 source/_posts/useful-vagrant-commands.md create mode 100644 source/_posts/using-feature-flags-in-drupal-development.md create mode 100644 source/_posts/using-imagecache-and-imagecrop-my-portfolio.md create mode 100644 source/_posts/using-laravel-collections-drupal.md create mode 100644 source/_posts/using-pcss-extension-postcss-webpack-encore.md create mode 100644 source/_posts/using-remote-files-when-developing-locally-stage-file-proxy-module.md create mode 100644 source/_posts/using-tailwind-css-your-drupal-theme.md create mode 100644 source/_posts/using-traefik-local-proxy-sculpin.md create mode 100644 source/_posts/using-transition-props-vuejs.md create mode 100644 source/_posts/weeknotes-2021-06-05.md create mode 100644 source/_posts/weeknotes-2021-06-12.md create mode 100644 source/_posts/weeknotes-2021-07-24.md create mode 100644 source/_posts/weeknotes-2021-08-06.md create mode 100644 source/_posts/what-git-flow.md create mode 100644 source/_posts/writing-article-linux-journal.md create mode 100644 source/_posts/writing-info-file-drupal-7-theme.md create mode 100644 source/_posts/writing-new-drupal-8-module-using-test-driven-development-tdd.md create mode 100644 source/_posts/zenophile.md diff --git a/app/config/sculpin_kernel.yml b/app/config/sculpin_kernel.yml index 54c021a8..7b459e5c 100644 --- a/app/config/sculpin_kernel.yml +++ b/app/config/sculpin_kernel.yml @@ -6,6 +6,6 @@ sculpin_content_types: podcast_episodes: permalink: /podcast/:basename/ posts: - enabled: false + permalink: /blog/:basename/ talks: permalink: /talks/:basename/ diff --git a/source/_includes/figure.html.twig b/source/_includes/figure.html.twig new file mode 100644 index 00000000..c8de55c1 --- /dev/null +++ b/source/_includes/figure.html.twig @@ -0,0 +1,8 @@ +
+ {{ image.alt }} + {% if caption %} +
+ {{ caption }} +
+ {% endif %} +
diff --git a/source/_includes/tweet.html.twig b/source/_includes/tweet.html.twig new file mode 100644 index 00000000..68bafebc --- /dev/null +++ b/source/_includes/tweet.html.twig @@ -0,0 +1,10 @@ +
+ +
diff --git a/source/_includes/youtube-video.html.twig b/source/_includes/youtube-video.html.twig index 4f731597..03489bca 100644 --- a/source/_includes/youtube-video.html.twig +++ b/source/_includes/youtube-video.html.twig @@ -1,6 +1,8 @@ - +
+ +
diff --git a/source/_layouts/post.html.twig b/source/_layouts/post.html.twig new file mode 100644 index 00000000..7ffcbe53 --- /dev/null +++ b/source/_layouts/post.html.twig @@ -0,0 +1,16 @@ +{% extends 'page' %} + +{% block content_wrapper %} + + + {{ parent() }} +{% endblock %} + +{% block content_bottom %} + {% include 'daily-email-form.html.twig' with { + intro: 'Sign up here and get more like this delivered straight to your inbox every day.', + title: 'Was this useful?', + } %} + + {% include 'about-me.html.twig' %} +{% endblock %} diff --git a/source/_posts/10-years-working-full-time-drupal-php.md b/source/_posts/10-years-working-full-time-drupal-php.md new file mode 100644 index 00000000..f0f36b75 --- /dev/null +++ b/source/_posts/10-years-working-full-time-drupal-php.md @@ -0,0 +1,29 @@ +--- +title: 10 years working full time with Drupal and PHP +excerpt: 10 years ago today, I started working for Horse & Country TV in what was my full-time Drupal development role. +tags: + - drupal + - personal + - php +date: 2020-07-19 +--- + +

10 years ago today, I started my first full-time Web Developer job, working for @HorseAndCountry on their (at the time) #Drupal 6 website.

— Oliver Davies (@opdavies) July 19, 2020
+ +10 years ago today, I started working for [Horse & Country TV](https://horseandcountry.tv) in what was my full-time Drupal development role. + +I'd been learning and working with Drupal for a couple of years prior to this, working on some personal and freelance projects, but when I was looking to move back to this area of Wales, this job on my doorstep was ideal. + +Initially starting as the sole Developer before another started a few months later, I remember being very excited to see and learn how this site has been built. Some of the main things that I remember working on was re-developing the Events section and adding paid events with [Ubercart](https://www.drupal.org/project/ubercart), and expanding my module development knowledge by adding a custom block that programmatically showed the current and next programme on the channel. + +As well as working with Drupal itself, it was a great opportunity to get more hands-on experience with Linux servers and to learn new tools such as [Git](https://git-scm.com) for version control. + +I also remember being asked to contribute to a public issue on Drupal.org as part of the interview process to demonstrate my debugging abilities. I decided to look at [this Drupal 6 issue](https://www.drupal.org/node/753898), and posted a comment with some updated code that I then forwarded on, and then uploaded a patch to the issue queue. This is still one of my favourite approaches for interviews, and one that I've used myself since when interviewing people for roles that use open source technologies. I much prefer this to working on internal, company specific coding tests, as it gives the interviewee some real world experience and exposure to the project itself and its community, rather than just how to _use_ it. + +Posting on a Drupal core issue and submitting patches was a bit scary at the time, but I think paved the way for me later contributing to core and other Drupal and open source projects. In fact, I was a Contribution Day mentor at DrupalCon Los Angeles in 2015 and helped someone get _their_ first commit to core when [a fix was committed to Drupal 8](https://git.drupalcode.org/project/drupal/commit/9cdd22c). + +After this role, I've worked for various agencies working primarily with Drupal and PHP, as well as for the [Drupal Association](https://www.drupal.org/assocation) itself. Whilst in recent years I've also started working with other frameworks like Symfony and Vue.js, Drupal and PHP has always been my core specialism. + +I've been very excited by the developments in both PHP and Drupal in recent versions, and I'm looking forward to the next 10 years working with them. + +Thank you Horse & Country for giving me the chance to start on my full-time Drupal journey! diff --git a/source/_posts/2014.md b/source/_posts/2014.md new file mode 100644 index 00000000..0ecae67b --- /dev/null +++ b/source/_posts/2014.md @@ -0,0 +1,84 @@ +--- +title: "2014" +date: 2015-03-20 +excerpt: A look back at 2014. +tags: + - drupal-association + - drupalcamp-london + - personal +tweets: true +--- + +A lot happened in 2014. Here are some of the main things that I'd like to +highlight. + +## Joined the Drupal Association + +This was the main thing for me this year, in May I left +[Precedent](http://precedent.com) and joined the +[Drupal Association](https://assoc.drupal.org). I work on the Engineering team, +focused mainly on [Drupal.org](https://www.drupal.org) but I've also done some +theming work on the DrupalCon [Amsterdam](http://amsterdam2014.drupal.org) and +[Latin America](http://latinamerica2015.drupal.org) websites, and some +pre-launch work on [Drupal Jobs](https://jobs.drupal.org). + +Some of the tasks that I've worked on so far are: + +- Fixing remaining issues from the Drupal.org Drupal 7 upgrade. +- Improving pages for + [Supporting Partners](https://www.drupal.org/supporters/partners), + [Technology Supporters](https://www.drupal.org/supporters/technology) and + [Hosting Partners](https://www.drupal.org/supporters/hosting). These + previously were manually updated pages using HTML tables, which are now + dynamic pages built with [Views](https://www.drupal.org/project/views) using + organisation nodes. +- Configuring human-readable paths for user profiles using + [Pathauto](https://www.drupal.org/project/pathauto). Only a small change, but + made a big difference to end-users. +- Migration of user data from profile values to fields, and various user profile + improvements. This was great because now we can do things like reference + mentors by their username and display their picture on your profile, as well + as show lists of peope listing a user as their mentor. This, I think, adds a + more personal element to Drupal.org because we can see the actual people and + not just a list of names on a page. + +I've started keeping a list of tasks that I've been involved with on my +[Work](/work/) page, and will be adding more things as I work on them. + +### Portland + +I was able to travel to Portland, Oregon twice last year to meet with the rest +of the Association staff. Both times I met new people and it was great to spend +some work and social time with everyone, and it was great to have everyone +together as a team. + +## My First DrupalCamp + +In February, I attended [DrupalCamp London](http://2014.drupalcamplondon.co.uk). +This was my first time attending a Camp, and I managed to attend some great +sessions as well as meet people who I'd never previously met in person. I was +also a volunteer and speaker, where I talked about +[Git Flow](/blog/what-git-flow/) - a workflow for managing your Git projects. + +{% include 'tweet' with { + content: '

Great presentation by @opdavies on git flow at #dclondon very well prepared and presented. pic.twitter.com/tDINp2Nsbn

— Greg Franklin (@gfranklin) March 2, 2014' +} %} + +I was also able to do a little bit of sprinting whilst I was there, reviewing +other people's modules and patches. + +Attending this and [DrupalCon Prague](https://prague2013.drupal.org) in 2013 +have really opened my eyes to the face-to-face side of the Drupal community, and +I plan on attending a lot more Camps and Cons in the future. + +## DrupalCon Amsterdam + +I was also able to travel to Holland and attend +[DrupalCon Amsterdam](https://amsterdam2014.drupal.org) along with other members +of Association staff. + +## DrupalCamp Bristol + +In October, we started planning for +[DrupalCamp Bristol](http://www.drupalcampbristol.co.uk). I'm one of the +founding Committee members, diff --git a/source/_posts/accessible-bristol-site.md b/source/_posts/accessible-bristol-site.md new file mode 100644 index 00000000..4c0d7891 --- /dev/null +++ b/source/_posts/accessible-bristol-site.md @@ -0,0 +1,30 @@ +--- +title: Accessible Bristol site launched +date: 2012-11-15 +excerpt: + I'm happy to report that the Accessible Bristol was launched this week, on + Drupal 7. +tags: + - accessibility + - accessible-bristol + - nomensa +--- + +I'm happy to announce that the +[Accessible Bristol](http://www.accessiblebristol.org.uk) website was launched +this week, on Drupal 7. The site has been developed over the past few months, +and uses the [User Relationships](http://drupal.org/project/user_relationships) +and [Privatemsg](http://drupal.org/project/privatemsg) modules to provide a +community-based platform where people with an interest in accessibility can +register and network with each other. + +The site has been developed over the past few months, and uses the +[User Relationships](http://drupal.org/project/user_relationships) and +[Privatemsg](http://drupal.org/project/privatemsg) modules to provide a +community-based platform where people with an interest in accessibility can +register and network with each other. + +The group is hosting a launch event on the 28th November at the Council House, +College Green, Bristol. Interested? More information is available at + or go to + to register. diff --git a/source/_posts/add-taxonomy-term-multiple-nodes-using-sql.md b/source/_posts/add-taxonomy-term-multiple-nodes-using-sql.md new file mode 100644 index 00000000..7b9ca026 --- /dev/null +++ b/source/_posts/add-taxonomy-term-multiple-nodes-using-sql.md @@ -0,0 +1,79 @@ +--- +title: Add a Taxonomy Term to Multiple Nodes Using SQL +date: 2010-07-07 +excerpt: How to add a new taxonomy term to multiple nodes in Drupal using SQL. +tags: + - database + - drupal-6 + - drupal-planet + - sequal-pro + - sql + - taxonomy +--- + +In preparation for my Blog posts being added to +[Drupal Planet](http://drupal.org/planet), I needed to create a new Taxonomy +term (or, in this case, tag) called 'Drupal Planet', and assign it to new +content to imported into their aggregator. After taking a quick look though my +previous posts, I decided that 14 of my previous posts were relevant, and +thought that it would be useful to also assign these the 'Drupal Planet' tag. + +I didn't want to manually open each post and add the new tag, so I decided to +make the changes myself directly into the database using SQL, and as a follow-up +to a previous post - +[Quickly Change the Content Type of Multiple Nodes using SQL](/blog/change-content-type-multiple-nodes-using-sql/). + +**Again, before changing any values within the database, ensure that you have an +up-to-date backup which you can restore if you encounter a problem!** + +The first thing I did was create the 'Drupal Planet' term in my Tags vocabulary. +I decided to do this via the administration area of my site, and not via the +database. Then, using [Sequel Pro](http://www.sequelpro.com), I ran the +following SQL query to give me a list of Blog posts on my site - showing just +their titles and nid values. + +```sql +SELECT title, nid FROM node WHERE TYPE = 'blog' ORDER BY title ASC; +``` + +I made a note of the nid's of the returned nodes, and kept them for later. I +then ran a similar query against the term_data table. This returned a list of +Taxonomy terms - showing the term's name, and it's unique tid value. + +```sql +SELECT NAME, tid FROM term_data ORDER BY NAME ASC; +``` + +The term that I was interested in, Drupal Planet, had the tid of 84. To confirm +that no nodes were already assigned a taxonomy term with this tid, I ran another +query against the database. I'm using aliases within this query to link the +node, term_node and term_data tables. For more information on SQL aliases, take +a look at . + +```sql +SELECT * FROM node n, term_data td, term_node tn WHERE td.tid = 84 AND n.nid = tn.nid AND tn.tid = td.tid; +``` + +As expected, it returned no rows. + +The table that links node and term_data is called term_node, and is made up of +the nid and vid columns from the node table, as well as the tid column from the +term_data table. Is it is here that the additional rows would need to be +entered. + +To confirm everything, I ran a simple query against an old post. I know that the +only taxonomy term associated with this post is 'Personal', which has a tid +value of 44. + +```sql +SELECT nid, tid FROM term_node WHERE nid = 216; +``` + +Once the query had confirmed the correct tid value, I began to write the SQL +Insert statement that would be needed to add the new term to the required nodes. +The nid and vid values were the same on each node, and the value of my taxonomy +term would need to be 84. + +Once this had completed with no errors, I returned to the administration area of +my Drupal site to confirm whether or not the nodes had been assigned the new +term. diff --git a/source/_posts/adding-custom-theme-templates-drupal-7.md b/source/_posts/adding-custom-theme-templates-drupal-7.md new file mode 100644 index 00000000..3387875f --- /dev/null +++ b/source/_posts/adding-custom-theme-templates-drupal-7.md @@ -0,0 +1,84 @@ +--- +title: Adding Custom Theme Templates in Drupal 7 +date: 2012-04-19 +excerpt: > + Today, I had a situation where I was displaying a list of teasers for news + article nodes. The article content type had several different fields assigned + to it, including main and thumbnail images. In this case, I wanted to have + different output and fields displayed when a teaser was displayed compared to + when a complete node was displayed. +tags: + - drupal + - drupal-planet +--- + +Today, I had a situation where I was displaying a list of teasers for news +article nodes. The article content type had several different fields assigned to +it, including main and thumbnail images. In this case, I wanted to have +different output and fields displayed when a teaser was displayed compared to +when a complete node was displayed. + +I have previously seen it done this way by adding this into in a node.tpl.php +file: + +```php +if ($teaser) { + // The teaser output. +} +else { + // The whole node output. +} +``` + +However, I decided to do something different and create a separate template file +just for teasers. This is done using the hook_preprocess_HOOK function that I +can add into my theme's template.php file. + +The function requires the node variables as an argument - one of which is +theme_hook_suggestions. This is an array of suggested template files that Drupal +looks for and attempts to use when displaying a node, and this is where I'll be +adding a new suggestion for my teaser-specific template. Using the `debug()` +function, I can easily see what's already there. + +```php +array ( + 0 => 'node__article', + 1 => 'node__343', + 2 => 'node__view__latest_news', + 3 => 'node__view__latest_news__page', +) +``` + +So, within my theme's template.php file: + +```php +/** + * Implementation of hook_preprocess_HOOK(). + */ +function mytheme_preprocess_node(&$variables) { + $node = $variables['node']; + + if ($variables['teaser']) { + // Add a new item into the theme_hook_suggestions array. + $variables['theme_hook_suggestions'][] = 'node__' . $node->type . '_teaser'; + } +} +``` + +After adding the new suggestion: + +```php +array ( + 0 => 'node__article', + 1 => 'node__343', + 2 => 'node__view__latest_news', + 3 => 'node__view__latest_news__page', + 4 => 'node__article_teaser', +) +``` + +Now, within my theme I can create a new node--article-teaser.tpl.php template +file and this will get called instead of the node--article.tpl.php when a teaser +is loaded. As I'm not specifying the node type specifically and using the +dynamic \$node->type value within my suggestion, this will also apply +for all other content types on my site and not just news articles. diff --git a/source/_posts/announcing-the-drupal-vm-generator.md b/source/_posts/announcing-the-drupal-vm-generator.md new file mode 100644 index 00000000..5b2a5855 --- /dev/null +++ b/source/_posts/announcing-the-drupal-vm-generator.md @@ -0,0 +1,104 @@ +--- +title: Announcing the Drupal VM Generator +date: 2016-02-15 +excerpt: For the past few weeks, I’ve been working on a personal side project based on Drupal VM - the Drupal VM Generator. +tags: + - drupal + - drupal-planet + - drupal-vm + - drupal-vm-generator + - symfony +--- + +For the past few weeks, I’ve been working on a personal side project based on +Drupal VM. It’s called the [Drupal VM Generator][1], and over the weekend I’ve +added the final features and fixed the remaining issues, and tagged the 1.0.0 +release. + +![](/images/blog/drupalvm-generate-repo.png) + +## What is Drupal VM? + +[Drupal VM][2] is a project created and maintained by [Jeff Geerling][3]. It’s a +[Vagrant][4] virtual machine for Drupal development that is provisioned using +[Ansible][5]. + +What is different to a regular Vagrant VM is that uses a file called +`config.yml` to configure the machine. Settings such as `vagrant_hostname`, +`drupalvm_webserver` and `drupal_core_path` are stored as YAML and passed into +the `Vagrantfile` and the `playbook.yml` file which is used when the Ansible +provisioner runs. + +In addition to some essential Ansible roles for installing and configuring +packages such as Git, MySQL, PHP and Drush, there are also some roles that are +conditional and only installed based on the value of other settings. These +include Apache, Nginx, Solr, Varnish and Drupal Console. + +## What does the Drupal VM Generator do? + +> The Drupal VM Generator is a Symfony application that allows you to quickly +> create configuration files that are minimal and use-case specific. + +Drupal VM comes with an [example.config.yml file][6] that shows all of the +default variables and their values. When I first started using it, I’d make a +copy of `example.config.yml`, rename it to `config.yml` and edit it as needed, +but a lot of the examples aren’t needed for every use case. If you’re using +Nginx as your webserver, then you don’t need the Apache virtual hosts. If you +are not using Solr on this project, then you don’t need the Solr variables. + +For a few months, I’ve kept and used boilerplace versions of `config.yml` - one +for Apache and one for Nginx. These are minimal, so have most of the comments +removed and only the variables that I regularly need, but these can still be +quite time consuming to edit each time, and if there are additions or changes +upstream, then I have two versions to maintain. + +The Drupal VM Generator is a Symfony application that allows you to quickly +create configuration files that are minimal and use-case specific. It uses the +[Console component][7] to collect input from the user, [Twig][8] to generate the +file, the [Filesystem component][9] to write it. + +Based on the options passed to it and/or answers that you provide, it generates +a custom, minimal `config.yml` file for your project. + +Here’s an example of it in action: + +!['An animated gif showing the interaction process and the resulting config.yml file'](/images/blog/drupalvm-generate-example-2.gif) + +You can also define options when calling the command and skip any or all +questions. Running the following would bypass all of the questions and create a +new file with no interaction or additional steps. + +# Where do I get it? + +The project is hosted on [GitHub][1], and there are installation instructions +within the [README][10]. + +
+ +The recommended method is via downloading the phar file (the same as Composer +and Drupal Console). You can also clone the GitHub repository and run the +command from there. I’m also wanting to upload it to Packagist so that it can be +included if you manage your projects with Composer. + +Please log any bugs or feature requests in the [GitHub issue tracker][11], and +I’m more than happy to receive pull requests. + +If you’re interested in contributing, please feel free to fork the repository +and start doing so, or contact me with any questions. + +**Update 17/02/16:** The autoloading issue is now fixed if you require the +package via Composer, and this has been tagged as the [1.0.1 release][12] + +[1]: https://github.com/opdavies/drupal-vm-generator +[2]: http://www.drupalvm.com +[3]: http://www.jeffgeerling.com +[4]: http://www.vagrantup.com +[5]: https://www.ansible.com +[6]: https://github.com/geerlingguy/drupal-vm/blob/master/example.config.yml +[7]: http://symfony.com/doc/current/components/console/introduction.html +[8]: http://twig.sensiolabs.org +[9]: http://symfony.com/doc/current/components/filesystem/introduction.html +[10]: + https://github.com/opdavies/drupal-vm-generator/blob/master/README.md#installation +[11]: https://github.com/opdavies/drupal-vm-generator/issues +[12]: https://github.com/opdavies/drupal-vm-generator/releases/tag/1.0.1 diff --git a/source/_posts/automating-sculpin-jenkins.md b/source/_posts/automating-sculpin-jenkins.md new file mode 100644 index 00000000..b3b16b5c --- /dev/null +++ b/source/_posts/automating-sculpin-jenkins.md @@ -0,0 +1,192 @@ +--- +title: Automating Sculpin Builds with Jenkins CI +date: 2015-07-21 +excerpt: How to use Jenkins to automate building Sculpin websites. +tags: + - jenkins + - sculpin +--- + +As part of re-building this site with [Sculpin](http://sculpin.io), I wanted to +automate the deployments, as in I wouldn't need to run a script like +[publish.sh](https://raw.githubusercontent.com/sculpin/sculpin-blog-skeleton/master/publish.sh) +locally and have that deploy my code onto my server. Not only did that mean that +my local workflow was simpler (update, commit and push, rather than update, +commit, push and deploy), but if I wanted to make a quick edit or hotfix, I +could log into GitHub or Bitbucket (wherever I decided to host the source code) +from any computer or my phone, make the change and have it deployed for me. + +I'd started using [Jenkins CI](http://jenkins-ci.org) during my time at the +Drupal Association, and had since built my own Jenkins server to handle +deployments of Drupal websites, so that was the logical choice to use. + +## Installing Jenkins and Sculpin + +If you don’t already have Jenkins installed and configured, I'd suggest using +[Jeff Geerling](http://jeffgeerling.com/) (aka geerlingguy)'s +[Ansible role for Jenkins CI](https://galaxy.ansible.com/list#/roles/440). + +I've also released an +[Ansible role for Sculpin](https://galaxy.ansible.com/list#/roles/4063) that +installs the executable so that the Jenkins server can run Sculpin commands. + +## Triggering a Build from a Git Commit + +I created a new Jenkins item for this task, and restricted where it could be run +to `master` (i.e. the Jenkins server rather than any of the nodes). + +### Polling from Git + +I entered the url to the +[GitHub repo](https://github.com/opdavies/oliverdavies.uk) into the **Source +Code Management** section (the Git option _may_ have been added by the +[Git plugin](https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin) that I have +installed). + +As we don’t need any write access back to the repo, using the HTTP URL rather +than the SSH one was fine, and I didn’t need to provide any additional +credentials. + +Also, as I knew that I’d be working a lot with feature branches, I entered +`*/master` as the only branch to build. This meant that pushing changes or +making edits on any other branches would not trigger a build. + +![Defining the Git repository in Jenkins](/images/blog/oliverdavies-uk-jenkins-git-repo.png) + +I also checked the **Poll SCM** option so that Jenkins would be routinely +checking for updated code. This essentially uses the same syntax as cron, +specifying minutes, hours etc. I entered `* * * * *` so that Jenkins would poll +each minute, knowing that I could make this less frequent if needed. + +This now that Jenkins would be checking for any updates to the repo each minute, +and could execute tasks if needed. + +### Building and Deploying + +Within the **Builds** section of the item, I added an _Execute Shell_ step, +where I could enter a command to execute. Here, I pasted a modified version of +the original publish.sh script. + +```bash +#!/bin/bash + +set -uex + +sculpin generate --env=prod --quiet +if [ $? -ne 0 ]; then echo "Could not generate the site"; exit 1; fi + +rsync -avze 'ssh' --delete output_prod/ prodwww2:/var/www/html/oliverdavies.uk/htdocs +if [ $? -ne 0 ]; then echo "Could not publish the site"; exit 1; fi +``` + +This essentially is the same as the original file, in that Sculpin generates the +site, and uses rsync to deploy it somewhere else. In my case, `prodwww2` is a +Jenkins node (this alias is configured in `/var/lib/jenkins/.ssh/config`), and +`/var/www/html/oliverdavies.uk/htdocs` is the directory from where my site is +served. + +## Building Periodically + +There is some dynamic content on my site, specifically on the Talks page. Each +talk has a date assigned to it, and within the Twig template, the talk is +positoned within upcoming or previous talks based on whether this date is less +or greater than the time of the build. + +The YAML front matter: + +```yaml +--- +... +talks: + - title: Test Drive Twig with Sculpin + location: DrupalCamp North +--- +``` + +The Twig layout: + +```twig +{% verbatim %} +{% for talk in talks|reverse if talk.date >= now %} + {# Upcoming talks #} +{% endfor %} + +{% for talk in talks if talk.date < now %} + {# Previous talks #} +{% endfor %} +{% endverbatim %} +``` + +I also didn’t want to have to push an empty commit or manually trigger a job in +Jenkins after doing a talk in order for it to be positioned in the correct place +on the page, so I also wanted Jenkins to schedule a regular build regardless of +whether or not code had been pushed, so ensure that my talks page would be up to +date. + +After originally thinking that I'd have to split the build steps into a separate +item and trigger that from a scheduled item, and amend my git commit item +accordingly, I found a **Build periodically** option that I could use within the +same item, leaving it intact and not having to make amends. + +I set this to `@daily` (the same `H H * * *` - `H` is a Jenkins thing), so that +the build would be triggered automatically each day without a commit, and deploy +any updates to the site. + +![Setting Jenkins to periodically build a new version of the site.](/images/blog/oliverdavies-uk-jenkins-git-timer.png) + +## Next Steps + +This workflow works great for one site, but as I roll out more Sculpin sites, +I'd like to reduce duplication. I see this mainly as I’ll end up creating a +separate `sculpin_build` item that’s decoupled from the site that it’s building, +and instead passing variables such as environment, server name and docroot path +as parameters in a parameterized build. + +I'll probably also take the raw shell script out of Jenkins and save it in a +text file that's stored locally on the server, and execute that via Jenkins. +This means that I’d be able to store this file in a separate Git repository with +my other Jenkins scripts and get the standard advantages of using version +control. + +## Update + +Since publishing this post, I've added some more items to the original build +script. + +### Updating Composer + +```bash +if [ -f composer.json ]; then + /usr/local/bin/composer install +fi +``` + +Updates project dependencies via +[Composer](https://getcomposer.org/doc/00-intro.md#introduction) if +composer.json exists. + +### Updating Sculpin Dependencies + +```bash +if [ -f sculpin.json ]; then + sculpin install +fi +``` + +Runs `sculpin install` on each build if the sculpin.json file exists, to ensure +that the required custom bundles and dependencies are installed. + +### Managing Redirects + +```bash +if [ -f scripts/redirects.php ]; then + /usr/bin/php scripts/redirects.php +fi +``` + +I've been working on a `redirects.php` script that generates redirects from a +.csv file, after seeing similar things in the +[Pantheon Documentation](https://github.com/pantheon-systems/documentation) and +[That Podcast](https://github.com/thatpodcast/thatpodcast.io) repositories. This +checks if that file exists, and if so, runs it and generates the source file +containing each redirect. diff --git a/source/_posts/back-future-gits-diff-apply-commands.md b/source/_posts/back-future-gits-diff-apply-commands.md new file mode 100644 index 00000000..72adade1 --- /dev/null +++ b/source/_posts/back-future-gits-diff-apply-commands.md @@ -0,0 +1,72 @@ +--- +title: Back to the future with Git’s diff and apply commands +date: 2018-04-23 +excerpt: How to revert files using Git, but as a new commit to prevent force pushing. +tags: + - git +--- + +This is one of those “there’s probably already a better way to do this” +situations, but it worked. + +I was having some issues this past weekend where, despite everything working +fine locally, a server was showing a “500 Internal Server” after I pushed some +changes to a site. In order to bring the site back online, I needed to revert +the site files back to the previous version, but as part of a new commit. + +The `git reset` commands removed the interim commits which meant that I couldn’t +push to the remote (force pushing, quite rightly, isn’t allowed for the +production branch), and using `git revert` was resulting in merge conflicts in +`composer.lock` that I’d rather have avoided if possible. + +This is what `git log --oneline -n 4` was outputting: + +``` +14e40bc Change webflo/drupal-core-require-dev version +fc058bb Add services.yml +60bcf33 Update composer.json and re-generate lock file +722210c More styling +``` + +`722210c` is the commit SHA that I needed to go back to. + +## First Solution + +My first solution was to use `git diff` to create a single patch file of all of +the changes from the current point back to the original commit. In this case, +I’m using `head~3` (four commits before `head`) as the original reference, I +could have alternatively used a commit ID, tag or branch name. + +``` +git diff head head~3 > temp.patch +git apply -v temp.patch +``` + +With the files are back in the former state, I can remove the patch, add the +files as a new commit and push them to the remote. + +``` +rm temp.patch + +git add . +git commit -m 'Back to the future' +git push +``` + +Although the files are back in their previous, working state, as this is a new +commit with a new commit SHA reference, there is no issue with the remote +rejecting the commit or needing to attempt to force push. + +## Second Solution + +The second solution is just a shorter, cleaner version of the first! + +Rather than creating a patch file and applying it, the output from `git diff` +can be piped straight into `git apply`. + +``` +git diff head~3 head | git apply -v +``` + +This means that there’s only one command to run and no leftover patch file, and +I can go ahead and add and commit the changes straight away. diff --git a/source/_posts/building-gmail-filters-in-php.md b/source/_posts/building-gmail-filters-in-php.md new file mode 100644 index 00000000..7aa50ecb --- /dev/null +++ b/source/_posts/building-gmail-filters-in-php.md @@ -0,0 +1,102 @@ +--- +title: Building Gmail Filters with PHP +date: 2016-07-15 +excerpt: How to use PHP to generate and export filters for Gmail. +tags: + - gmail + - php +promoted: true +--- + +Earlier this week I wrote a small PHP library called [GmailFilterBuilder][0] +that allows you to write Gmail filters in PHP and export them to XML. + +I was already aware of a Ruby library called [gmail-britta][1] that does the +same thing, but a) I’m not that familiar with Ruby so the syntax wasn’t that +natural to me - it’s been a while since I wrote any Puppet manifests, and b) it +seemed like a interesting little project to work on one evening. + +The library contains two classes - `GmailFilter` which is used to create each +filter, and `GmailFilterBuilder` that parses the filters and generates the XML +using a [Twig][2] template. + +## Usage + +For example: + +```php +# test.php + +require __DIR__ '/vendor/autoload.php'; + +use Opdavies\GmailFilterBuilder\Builder; +use Opdavies\GmailFilterBuilder\Filter; + +$filters = []; + +$filters[] = Filter::create() + ->has('from:example@test.com') + ->labelAndArchive('Test') + ->neverSpam(); + +new Builder($filters); +``` + +In this case, an email from `example@test.com` would be archived, never marked +as spam, and have a label of "Test" added to it. + +With this code written, and the GmailFilterBuilder library installed via +Composer, I can run `php test.php` and have the XML written to the screen. + +This can also be written to a file - `php test.php > filters.xml` - which can +then be imported into Gmail. + +## Twig Extensions + +I also added a custom Twig extension that I moved into a separate +[twig-extensions][5] library so that I and other people can re-use it in other +projects. + +It’s a simple filter that accepts a boolean and returns `true` or `false` as a +string, but meant that I could remove three ternary operators from the template +and replace them with the `boolean_string` filter. + +Before: + +```twig +{% verbatim %} +{{ filter.isArchive ? 'true' : 'false' }} +{% endverbatim %} +``` + +After: + +```twig +{% verbatim %} +{{ filter.isArchive|boolean_string }} +{% endverbatim %} +``` + +This can then be used to generate output like this, whereas having blank values +would have resulted in errors when importing to Gmail. + +```xml + +``` + +## Example + +For a working example, see my personal [gmail-filters][3] repository on GitHub. + +## Resources + +- [The GmailFilterBuilder library on Packagist][4] +- [My Gmail filters on GitHub][3] +- [My Twig Extensions on Packagist][5] + +[0]: https://github.com/opdavies/gmail-filter-builder +[1]: https://github.com/antifuchs/gmail-britta +[2]: http://twig.sensiolabs.org +[3]: https://github.com/opdavies/gmail-filters +[4]: https://packagist.org/packages/opdavies/gmail-filter-builder +[5]: https://packagist.org/packages/opdavies/twig-extensions diff --git a/source/_posts/building-oliverdavies-uk-1-initial-setup.md b/source/_posts/building-oliverdavies-uk-1-initial-setup.md new file mode 100644 index 00000000..f9fcf680 --- /dev/null +++ b/source/_posts/building-oliverdavies-uk-1-initial-setup.md @@ -0,0 +1,19 @@ +--- +title: 'Building oliverdavies.uk with Sculpin: Part 1 - initial setup and configuration' +excerpt: | + First part of the "Building oliverdavies.uk" series, covering the initial + Sculpin setup and configuration. +tags: [sculpin] +draft: true +date: ~ +--- + +Based on . + +Uses . + +`app/config/sculpin_kernel.yml`: + +`app/config/sculpin_site.yml`: + +`app/config/sculpin_site_prod.yml`: diff --git a/source/_posts/building-the-new-phpsw-website.md b/source/_posts/building-the-new-phpsw-website.md new file mode 100644 index 00000000..76484a54 --- /dev/null +++ b/source/_posts/building-the-new-phpsw-website.md @@ -0,0 +1,37 @@ +--- +title: Building the new PHPSW Website +date: 2018-02-28 +excerpt: + Earlier this week we had another hack night, working on the new PHPSW user + group website. +tags: + - phpsw + - symfony + - tailwind-css +has_tweets: true +--- + +Earlier this week we had another hack night, working on the new [PHPSW user +group][0] website. + +
+ +
+ +It’s built with Symfony so it’s naturally using Twig for templating. I’ve become +a big fan of the utility based approach to CSS and [Tailwind CSS][1] in +particular, so I’m using that for all of the styling, and using [Webpack +Encore][2] to compile all of the assets. + +We have an integration with Meetup.com which we’re using to pull all of our +previous event data and store them as JSON files for Symfony to parse and +render, which it then uses to generate static HTML to upload onto the server. + +We’re in the process of populating all of the past data, but look out for a v1 +launch soon. In the meantime, feel free to take a peek at our [GitHub +repository][3]. + +[0]: https://phpsw.uk +[1]: https://tailwindcss.com +[2]: https://github.com/symfony/webpack-encore +[3]: https://github.com/phpsw/phpsw-ng diff --git a/source/_posts/change-content-type-multiple-nodes-using-sql.md b/source/_posts/change-content-type-multiple-nodes-using-sql.md new file mode 100644 index 00000000..01744dc2 --- /dev/null +++ b/source/_posts/change-content-type-multiple-nodes-using-sql.md @@ -0,0 +1,42 @@ +--- +title: Change the Content Type of Multiple Nodes Using SQL +date: 2010-07-01 +excerpt: + In this post, I will be changing values within my Drupal 6 site's database to quickly change the content type of multiple nodes. +tags: + - content-types + - database + - drupal + - drupal-6 + - drupal-planet + - sequel-pro + - sql +--- + +In this post, I will be changing values within my Drupal 6 site's database to +quickly change the content type of multiple nodes. I will be using a test +development site with the core Blog module installed, and converting Blog posts +to a custom content type called 'News article'. + +**Before changing any values within the database, ensure that you have an +up-to-date backup which you can restore if you encounter a problem!** + +To begin with, I created the 'News article' content type, and then used the +Devel Generate module to generate some Blog nodes. + +Using [Sequel Pro](http://www.sequelpro.com), I can query the database to view +the Blog posts (you can also do this via the +[Terminal](http://guides.macrumors.com/Terminal) in a Mac OS X/Linux, +[Oracle SQL Developer](http://www.oracle.com/technology/software/products/sql/index.html) +on Windows, or directly within +[phpMyAdmin](http://www.phpmyadmin.net/home_page/index.php)): + +Using an SQL 'Update' command, I can change the type value from 'blog' to +'article'. This will change every occurance of the value 'blog'. If I wanted to +only change certain nodes, I could add a 'Where' clause to only affect nodes +with a certain nid or title. + +Now, when I query the database, the type is shown as 'article'. + +Now, when I go back into the administration section of my site and view the +content, the content type now shows at 'News article'. diff --git a/source/_posts/checking-if-user-logged-drupal-right-way.md b/source/_posts/checking-if-user-logged-drupal-right-way.md new file mode 100644 index 00000000..071fc89d --- /dev/null +++ b/source/_posts/checking-if-user-logged-drupal-right-way.md @@ -0,0 +1,68 @@ +--- +title: Checking if a user is logged into Drupal (the right way) +date: 2013-01-09 +excerpt: How to check if a user is logged in by using Drupal core API functions. +tags: + - drupal + - drupal-6 + - drupal-7 + - drupal-planet + - php +--- + +I see this regularly when working on Drupal sites when someone wants to check +whether the current user is logged in to Drupal (authenticated) or not +(anonymous). + +```php +global $user; +if ($user->uid) { + // The user is logged in. +} +``` + +or + +```php +global $user; +if (!$user->uid) { + // The user is not logged in. +} +``` + +The better way to do this is to use the +[user_is_logged_in()](http://api.drupal.org/api/drupal/modules!user!user.module/function/user_is_logged_in/7) +function. + +```php +if (user_is_logged_in()) { + // Do something. +} +``` + +This returns a boolean (TRUE or FALSE) depending or not the user is logged in. +Essentially, it does the same thing as the first example, but there's no need to +load the global variable. + +A great use case for this is within a `hook_menu()` implementation within a +custom module. + +```php +/** + * Implements hook_menu(). + */ +function mymodule_menu() { + $items['foo'] = array( + 'title' => 'Foo', + 'page callback' => 'mymodule_foo', + 'access callback' => 'user_is_logged_in', + ); + + return $items; +} +``` + +There is also a +[user_is_anonymous()](http://api.drupal.org/api/drupal/modules!user!user.module/function/user_is_anonymous/7) +function if you want the opposite result. Both of these functions are available +in Drupal 6 and higher. diff --git a/source/_posts/checkout-specific-revision-svn-command-line.md b/source/_posts/checkout-specific-revision-svn-command-line.md new file mode 100644 index 00000000..c3019c01 --- /dev/null +++ b/source/_posts/checkout-specific-revision-svn-command-line.md @@ -0,0 +1,22 @@ +--- +title: Checkout a specific revision from SVN from the command line +date: 2012-05-23 +excerpt: How to checkout a specific revision from a SVN (Subversion) repository. +tags: + - svn + - version-control +--- + +How to checkout a specific revision from a SVN (Subversion) repository. + +If you're checking out the repository for the first time: + +```bash +$ svn checkout -r 1234 url://repository/path +``` + +If you already have the repository checked out: + +```bash +$ svn up -r 1234 +``` diff --git a/source/_posts/cleanly-retrieving-user-profile-data-using-entity-metadata-wrapper.md b/source/_posts/cleanly-retrieving-user-profile-data-using-entity-metadata-wrapper.md new file mode 100644 index 00000000..4484c1a5 --- /dev/null +++ b/source/_posts/cleanly-retrieving-user-profile-data-using-entity-metadata-wrapper.md @@ -0,0 +1,38 @@ +--- +title: Cleanly retrieving user profile data using an Entity Metadata Wrapper +excerpt: How to use Drupal 7's EntityMetadataWrapper to cleanly retrieve user profile field data. +tags: + - drupal + - drupal-7 + - drupal planet + - php +date: 2021-02-23 +--- + +Today I needed to load some Drupal user data via a [profile2](https://www.drupal.org/project/profile2) profile. When looking into this, most resources that I found suggest using this approach and calling the `profile2_load_by_user()` function directly and passing in the user object: + + +```php +$account = user_load(...); + +$accountWrapper = new EntityDrupalWrapper('user', $account); +// or `$accountWrapper = entity_metadata_wrapper('user', $account); + +$profile = profile2_load_by_user($account->value()); +// or `$profile = profile2_load_by_user($account);` + +$profileWrapper = new EntityDrupalWrapper('profile2', $profile); + +$firstName = $profileWrapper->get('field_first_name')->value(); +``` + +This though requires a few steps, and as I'm a fan of object-orientated code and Entity Metadata Wrappers, I wanted to find a cleaner solution. + +This is my preferred method that uses method chaining. It returns the same value, is less code, and in my opinion, it's cleaner and easier to read. + +```php +$firstName = $accountWrapper + ->get('profile_user_basic') + ->get('field_first_name') + ->value(); +``` diff --git a/source/_posts/conditional-email-addresses-webform.md b/source/_posts/conditional-email-addresses-webform.md new file mode 100644 index 00000000..dda57b8e --- /dev/null +++ b/source/_posts/conditional-email-addresses-webform.md @@ -0,0 +1,29 @@ +--- +title: Conditional Email Addresses in a Webform +date: 2010-05-06 +excerpt: + How to send webform emails to a different email address based on another + field. +tags: + - conditional-email + - drupal-6 + - drupal-planet + - webform +--- + +I created a new Webform to serve as a simple Contact form, but left the main +configuration until after I created the form components. I added 'Name', +'Email', 'Subject' and 'Message' fields, as well as a 'Category' select list. +Below 'Options', I entered each of my desired options in the following format: + +```ini +Email address|Visible name +``` + +I went back to the form configuration page and expanded 'Conditional Email +Recipients', and selected my Category. Note that the standard 'Email To' field +above it needs to be empty. Originally, I made the mistake of leaving addresses +in that field which resulted in people being sent emails regardles of which +category was selected. I then configured the rest of the form. + +Then, when I went to the finished form, the category selection was available. diff --git a/source/_posts/configuring-the-reroute-email-module.md b/source/_posts/configuring-the-reroute-email-module.md new file mode 100644 index 00000000..27ece0a8 --- /dev/null +++ b/source/_posts/configuring-the-reroute-email-module.md @@ -0,0 +1,70 @@ +--- +title: Configuring the Reroute Email Module +date: 2014-12-22 +excerpt: + How to configure the Reroute Email module, to prevent sending emails to real + users from your pre-production sites! +tags: + - drupal + - drupal-6 + - drupal-7 + - drupal-planet + - email +draft: true +--- + +[Reroute Email](https://www.drupal.org/project/reroute_email) module uses +`hook_mail_alter()` to prevent emails from being sent to users from +non-production sites. It allows you to enter one or more email addresses that +will receive the emails instead of delivering them to the original user. + +> This is useful in case where you do not want email sent from a Drupal site to +> reach the users. For example, if you copy a live site to a test site for the +> purpose of development, and you do not want any email sent to real users of +> the original site. Or you want to check the emails sent for uniform +> formatting, footers, ...etc. + +As we don't need the module configured on production (we don't need to reroute +any emails there), it's best to do this in code using settings.local.php (if you +have one) or the standard settings.php file. + +The first thing that we need to do is to enable rerouting. Without doing this, +nothing will happen. + +```php +$conf['reroute_email_enable'] = TRUE; +``` + +The next option is to whether to show rerouting description in mail body. I +usually have this enabled. Set this to TRUE or FALSE depending on your +preference. + +```php +$conf['reroute_email_enable_message'] = TRUE; +``` + +The last setting is the email address to use. If you're entering a single +address, you can add it as a simple string. + +```php +$conf['reroute_email_address'] = 'person1@example.com'; +``` + +In this example, all emails from the site will be rerouted to +person1@example.com. + +If you want to add multiple addresses, these should be added in a +semicolon-delimited list. Whilst you could add these also as a string, I prefer +to use an array of addresses and the `implode()` function. + +```php +$conf['reroute_email_address'] = implode(';', array( + 'person1@example.com', + 'person2@example.com', + 'person3@example.com', +)); +``` + +In this example, person2@example.com and person3@example.com would receive their +emails from the site as normal. Any emails to addresses not in the array would +continue to be redirected to person1@example.com. diff --git a/source/_posts/continuous-integration-vs-continuous-integration.md b/source/_posts/continuous-integration-vs-continuous-integration.md new file mode 100644 index 00000000..d2020c53 --- /dev/null +++ b/source/_posts/continuous-integration-vs-continuous-integration.md @@ -0,0 +1,46 @@ +--- +title: Continuous Integration vs Continuous Integration +excerpt: My views on the definitions of "continuous integration". +tags: + - git +date: 2021-10-07 +--- + +![A meme with Spider-Man pointing at Spider-Man, both labelled with 'Continuous Integration'](/images/blog/continuous-integration-spiderman.jpg) + +There seem to be two different definitions for the term "continuous integration" (or "CI") that I've come across whilst reading blogs, listening to podcasts, and watching video tutorials. + +## Tooling + +The first is around remote tools such as GitHub Actions, GitLab CI, Bitbucket Pipelines, Circle CI, and Jenkins, which automatically run tasks whenever you push or merge (or "integrate") code - such as code linting, performing static analysis checks, running automated tests, or building a deployment artifact. + +These focus on code quality and replicate steps that you can run locally, ensuring that the build is successful and that if the CI checks pass then the code can be deployed. + +My issue with this definition is that it may not be continuous. You could push code once a day or once a year, and it would perform the same checks and have the same outcomes and benefits. + +## Workflow + +The second definition isn't about tools - it's about how often you update, merge and push code (which commonly leads to feature branch vs trunk-based development, and Git Flow vs GitHub Flow discussions). How often are you pulling in the latest code, testing it with your local changes, and pushing your code for everyone else to see? + +If you're using feature branches, how long do they last, and how quickly are they merged into the main branch? + +Weekly? Daily? Hourly? + +The workflow definition doesn't need GitHub, GitLab, or Bitbucket to run checks - it's about keeping your local code continuously (or as often as possible) updated and integrated with the remote code. + +This ensures that you're developing from the latest stable version and not one that is days or weeks out of date. + +This means that merge conflicts and much less common as you're always pulling in the latest code and ensuring that it can be integrated. + +## Conclusion + +One definition isn't dependent on the other. + +You don't need the tooling and automation to use a continuous integration workflow, but I'd recommend it. It's useful to know and have confidence that the build passes, especially if you're pulling and pushing code several times a day, but it isn't a prerequisite. + +If you're working on a new feature or fixing a bug, pull down the latest code, +test your changes, and push it back as often as possible. + +If you watch a video, read a blog post, or listen to a podcast about continuous integration or "How to set up CI", remember that it's not just about the tooling. + +There's a different workflow and mindset to consider that introduces other complementary concepts such as automated testing and test-driven development, pair and mob programming, feature flags, and continuous delivery. diff --git a/source/_posts/create-better-photo-gallery-drupal-part-1.md b/source/_posts/create-better-photo-gallery-drupal-part-1.md new file mode 100644 index 00000000..3566cf5d --- /dev/null +++ b/source/_posts/create-better-photo-gallery-drupal-part-1.md @@ -0,0 +1,161 @@ +--- +title: Create a Better Photo Gallery in Drupal - Part 1 +date: 2010-08-11 +excerpt: + How I started converting and migrating a Coppermine photo gallery into Drupal. +tags: + - cck + - drupal + - drupal-6 + - drupal-planet + - photo-gallery + - sequel-pro + - sql + - views + - views-attach +--- + +Recently, I converted a client's static HTML website, along with their +Coppermine Photo Gallery, into a Drupal-powered website. + +Over the next few posts, I'll be replicating the process that I used during the +conversion, and how I added some additional features to my Drupal gallery. + +To begin with, I created my photo gallery as described by +[Jeff Eaton](http://www.lullabot.com/about/team/jeff-eaton) in +[this screencast](http://www.lullabot.com/articles/photo-galleries-views-attach), +downloaded all my client's previous photos via FTP, and quickly added them into +the new gallery using the +[Imagefield Import](http://drupal.org/project/imagefield_import) module (which I +mentioned +[previously](/blog/quickly-import-multiples-images-using-imagefieldimport-module/)). + +When I compare this to the previous gallery, I can see several differences which +I'd like to include. The first of which is the number of photos in each gallery, +and the date that the most recent photo was added. + +To do this, I'd need to query my website's database. To begin with, I wanted to +have a list of all the galleries on my site which are published, and what +they're unique node ID values are. To do this, I opened Sequel Pro and entered +the following code: + +```sql +SELECT title +AS title, nid +AS gallery_idFROM node +WHERE type = 'gallery' +AND status = 1; +``` + +As the nid value of each gallery corresponds with the 'field_gallery_nid' field +within the content_type_photo field, I can now query the database and retrieve +information about each specific gallery. + +For example, using [aliasing](http://www.w3schools.com/sql/sql_alias.asp) within +my SQL statement, I can retrieve a list of all the published photos within the +'British Squad 2008' gallery by using the following code: + +```sql +SELECT n.title, n.nid, p.field_gallery_nid +FROM node n, content_type_photo p +WHERE p.field_gallery_nid = 105 +AND n.status = 1 +AND n.nid = p.nid; +``` + +I can easily change this to count the number of published nodes by changing the +first line of the query to read SELECT COUNT(\*). + +```sql +SELECT COUNT(*) +FROM node n, content_type_photo p +WHERE p.field_gallery_nid = 105 +AND n.status = 1 +AND n.nid = p.nid; +``` + +As I've used the [Views Attach](http://drupal.org/project/views_attach) module, +and I'm embedding the photos directly into the Gallery nodes, I easily add this +to each gallery by creating a custom node-gallery.tpl.php file within my theme. +I can then use the following PHP code to retrieve the node ID for that specific +gallery: + +```php + +``` + +I can then use this variable as part of my next query to count the number of +photos within that gallery, similar to what I did earlier. + +```php + +``` + +Next, I wanted to display the date that the last photo was displayed within each +album. This was done by using a similar query that also sorted the results in a +descending order, and limited it to one result - effectively only returning the +created date for the newest photo. + +```php + +``` + +This was all then added into a 'print' statement which displayed it into the +page. + +```php +There are currently ' . $selected_gallery_total . ' photos in this gallery.'; + $output .= 'Last one added on ' . $latest_photo . ''; + print $output; +} +?> +``` + +OK, so let's take a look at the Gallery so far: + +You will notice that the returned date value for the latest photo added is +displaying the UNIX timestamp instead of in a more readable format. This can be +changed by altering the 'print' statement to include a PHP 'date' function: + +```php +There are currently ' . $selected_gallery_total . ' photos in this gallery.'; + $output .= 'Last one added on ' . date("l, jS F, Y", $latest_photo) . '.'; + print $output; +} +?> +``` + +The values that I've entered are from +[this page](http://php.net/manual/en/function.date.php) on PHP.net, and can be +changed according on how you want the date to be displayed. + +As I've added all of these photos today, then the correct dates are being +displayed. However, on the client's original website, the majority of these +photos were pubished several months or years ago, and I'd like the new website +to still reflect the original created dates. As opposed to modifying each +individual photograph, I'll be doing this in bulk in my next post. diff --git a/source/_posts/create-better-photo-gallery-drupal-part-2.md b/source/_posts/create-better-photo-gallery-drupal-part-2.md new file mode 100644 index 00000000..9bc6e0b4 --- /dev/null +++ b/source/_posts/create-better-photo-gallery-drupal-part-2.md @@ -0,0 +1,58 @@ +--- +title: Create a Better Photo Gallery in Drupal - Part 2 +date: 2010-08-17 +excerpt: Updating the galleries’ created and modified dates. +tags: + - drupal-6 + - drupal-planet + - photo-gallery + - sequel-pro + - sql +--- + +At the end of my last post, I'd finished creating the first part of the new +photo gallery, but I wanted to change the dates of the published photos to +reflect the ones on the client's original website. + +Firstly, I'll refer to the previous list of published galleries that I created +before, and create something different that also displays the created and +modified dates. Picking the node ID of the required gallery, I used the +following SQL query to display a list of photos. + +```sql +SELECT n.title, n.nid, n.created, n.changed, p.field_gallery_nid +FROM node n, content_type_photo pWHERE n.type = 'photo' +AND p.field_gallery_nid = 103AND n.nid = p.nid +ORDER BY n.nid ASC; +``` + +When I look back at the old photo gallery, I can see that the previous 'last +added' date was June 27, 2008. So, how do I update my new photos to reflect that +date? Using , I can enter the +required date in its readable format, and it will give me the equivilent UNIX +timestamp. To keep things relatively simple, I'll set all photos within this +gallery to the same time. + +The result that I'm given is '1217149200'. I can now use an UPDATE statement +within another SQL query to update the created and modified dates. + +```sql +UPDATE node +INNER JOIN content_type_photo +ON node.nid = content_type_photo.nid +SET + node.created = 1217149200, + node.changed = 1217149200 +WHERE content_type_photo.field_gallery_nid = 103 +``` + +Now when I query the database, both the created and modified dates have been +updated, and when I return to the new photo gallery, the updated value is being +displayed. + +Once the changes have been applied, it's a case of repeating the above process +for each of the required galleries. + +In the next post, I'll explain how to add a count of published galleries and +photos on the main photo gallery page, as well as how to install and configure +the [Shadowbox](http://drupal.org/project/shadowbox) module. diff --git a/source/_posts/create-better-photo-gallery-drupal-part-21.md b/source/_posts/create-better-photo-gallery-drupal-part-21.md new file mode 100644 index 00000000..d4ec05c4 --- /dev/null +++ b/source/_posts/create-better-photo-gallery-drupal-part-21.md @@ -0,0 +1,64 @@ +--- +title: Create a Better Photo Gallery in Drupal - Part 2.1 +date: 2010-10-22 +excerpt: The missing code to get totals of galleries and photos. +tags: + - drupal +--- + +Today, I realised that I hadn't published the code that I used to create the +total figures of galleries and photos at the top of the gallery (I said at the +end of +[Part 2](/blog/create-better-photo-gallery-drupal-part-2/ 'Create a Better Photo Gallery in Drupal - Part 2') +that I'd include it in +[Part 3](/blog/create-better-photo-gallery-drupal-part-3/ 'Create a Better Photo Gallery in Drupal - Part 3'), +but I forgot). So, here it is: + +```php + +``` + +It was applied to the view as a header which had the input format set to PHP +code. diff --git a/source/_posts/create-better-photo-gallery-drupal-part-3.md b/source/_posts/create-better-photo-gallery-drupal-part-3.md new file mode 100644 index 00000000..bac654ce --- /dev/null +++ b/source/_posts/create-better-photo-gallery-drupal-part-3.md @@ -0,0 +1,49 @@ +--- +title: Create a Better Photo Gallery in Drupal - Part 3 +date: 2010-10-13 +excerpt: Grouping galleries by category. +tags: + - drupal +--- + +The next part of the new gallery that I want to implement is to group the +galleries by their respective categories. The first step is to edit my original +photo_gallery view and add an additional display. + +I've called it 'Taxonomy', and it's similar to the original 'All Galleries' +view. The differences are that I've added the taxonomy term as an argument, +removed the header, and updated the path to be `gallery/%`. The other thing that +I need to do is overwrite the output of the original 'All Galleries' View by +creating a file called `views-view--photo-gallery--page-1.tpl.php` and placing +it within my theme directory. + +Within that file, I can remove the standard content output. This still outputs +the heading information from the original View. I can now use the function +called 'views_embed_view' to embed my taxonomy display onto the display. The +views_embed_view function is as follows: + +```php + +``` + +So, to display the galleries that are assigned the taxonomy of 'tournaments', I +can use the following: + +```php + +``` + +To reduce the amount of code needed, I can use the following 'while' loop to +generate the same code for each taxonomy term. It dynamically retrieves the +relevant taxonomy terms from the database, and uses each name as the argument +for the view. + +```php +' . $term['name'] . ''; + print views_embed_view('gallery', 'page_2', $term['name']); +} +?> +``` diff --git a/source/_posts/create-block-social-media-icons-using-cck-views-and-nodequeue.md b/source/_posts/create-block-social-media-icons-using-cck-views-and-nodequeue.md new file mode 100644 index 00000000..fa045366 --- /dev/null +++ b/source/_posts/create-block-social-media-icons-using-cck-views-and-nodequeue.md @@ -0,0 +1,44 @@ +--- +title: Create a Block of Social Media Icons using CCK, Views and Nodequeue +date: 2010-06-23 +excerpt: How to create a block of social media icons in Drupal. +tags: + - drupal + - drupal-6 + - drupal-planet + - nodequeue + - oliverdavies.co.uk + - views +--- + +I recently decided that I wanted to have a block displayed in a sidebar on my +site containing icons and links to my social media profiles - +[Twitter](http://twitter.com/opdavies), [Facebook](http://facebook.com/opdavies) +etc. I tried the [Follow](http://drupal.org/project/follow) module, but it +lacked the option to add extra networks such my +[Drupal.org](http://drupal.org/user/381388) account, and my +[RSS feed](http://oliverdavies.co.uk/rss.xml). I started to create my own +version, and then found +[this Blog post](http://www.hankpalan.com/blog/drupal-themes/add-your-social-connections-drupal-icons) +by Hank Palan. + +I created a 'Social icon' content type with the body field removed, and with +fields for a link and image - then downloaded the favicons from the appropriate +websites to use. + +However, instead of using a custom template (node-custom.tpl.php) file, I used +the Views module. + +I added fields for the node titles, and the link from the node's content. Both +of these are excluded from being displayed on the site. I then re-wrote the +output of the Icon field to create the link using the URL, and using the node's +title as the image's alternative text and the link's title. + +I also used the [Nodequeue](http://drupal.org/project/nodequeue) module to +create a nodequeue and arrange the icons in the order that I wanted them to be +displayed. Once this was added as a relationship within my View, I was able to +use node's position in the nodequeue as the sort criteria. + +To complete the process, I used the +[CSS Injector](http://drupal.org/project/css_injector) module to add some +additional CSS styling to position and space out the icons. diff --git a/source/_posts/create-flickr-photo-gallery-using-feeds-cck-views.md b/source/_posts/create-flickr-photo-gallery-using-feeds-cck-views.md new file mode 100644 index 00000000..560f08bb --- /dev/null +++ b/source/_posts/create-flickr-photo-gallery-using-feeds-cck-views.md @@ -0,0 +1,71 @@ +--- +title: Create a Flickr Photo Gallery Using Feeds, CCK and Views +date: 2010-06-28 +excerpt: + In this tutorial, I'll show you how to create a photo gallery which uses + photos imported from Flickr. +tags: + - drupal-planet + - drupal-6 + - photo-gallery + - views + - cck + - imagecache + - feeds + - filefield + - flickr + - imagefield +--- + +In this tutorial, I'll show you how to create a photo gallery which uses photos +imported from [Flickr](http://www.flickr.com). + +The modules that I'll use to create the Gallery are: + +- [CCK](http://drupal.org/project/cck) +- [Feeds](http://drupal.org/project/feeds) +- [Feeds Image Grabber](http://drupal.org/project/feeds_imagegrabber) +- [FileField](http://drupal.org/project/filefield) +- [ImageAPI](http://drupal.org/project/imageapi) +- [ImageCache](http://drupal.org/project/imagecache) +- [ImageField](http://drupal.org/project/imagefield) +- [Views](http://drupal.org/project/views) + +The first thing that I did was to create a content type to store my imported +images. I named it 'Photo', removed the Body field, and added an Image field. + +Next, I installed and configured the Feeds and Image Grabber module. I used an +overridden default Feed to import my photos from Flickr using the following +settings: + +- **Basic settings:** I changed the Refresh time to 15 minutes. +- **Processor settings:** I changed the content type to 'Photo', and the + author's name from 'anonymous'. +- **Processor mapping:** I added a new mapping from 'Item URL (link)' to 'Photo + (FIG)'. The Photo FIG target is added by the Image Grabber module. + +Next, I needed to create the actual Feed, which I did by clicking 'Import' +within the Navigation menu, and clicking 'Feed'. I gave it a title, entered the +URL to my RSS feed from Flickr, and enabled the Image Grabber for this feed. + +Once the Feed is created, the latest 20 images from the RSS feed are imported +and 20 new Photos nodes are created. In the example below, the image with the +'Photo' label is the Image field mapped by the Image Grabber module. It is this +image that I'll be displaying within my Gallery. + +With the new Photo nodes created, I then created the View to display them. + +The View selects the image within the Photo content type, and displays in it a +grid using an ImageCache preset. The View is limited to 20 nodes per page, and +uses a full pager if this is exceeded. The nodes are sorted by the descending +post date, and filtered by whether or not they are published, and only to +include Photo nodes. + +As an additional effect, I also included the 'Feeds Item - Item Link' field, +which is basically the original link from the RSS feed. By checking the box the +exclude the item from the display, it is not shown, but makes the link available +to be used elsewhere. By checking the box 'Re-write the output for this field' +on the 'Content: Photo' field, I was able to add the replacement token (in this +case, [url]) as the path for a link around each image. This meant that when +someone clicked a thumbnail of a photo, they were directed to the Flickr website +instead of the node within my Drupal site. diff --git a/source/_posts/create-multigroups-drupal-7-using-field-collections.md b/source/_posts/create-multigroups-drupal-7-using-field-collections.md new file mode 100644 index 00000000..7a754cc9 --- /dev/null +++ b/source/_posts/create-multigroups-drupal-7-using-field-collections.md @@ -0,0 +1,59 @@ +--- +title: Create Multigroups in Drupal 7 using Field Collections +date: 2011-08-28 +excerpt: + How to replicate CCK’s multigroups in Drupal 7 using the Field Collections + module. +tags: + - cck + - drupal-7 + - drupal-planet + - entity-api + - field-collection + - fields + - multigroup +--- + +One of my favourite things lately in Drupal 6 has been CCK 3, and more +specifically, the Content Multigroups sub-module. Basically this allows you to +create a fieldset of various CCK fields, and then repeat that multiple times. +For example, I use it on this site whist creating invoices for clients. I have a +fieldset called 'Line Item', containing 'Description', 'Quantity' and 'Price' +fields. With a standard fieldset, I could only have one instance of each field - +however, using a multigroup, I can create multiple groups of line items which I +then use within the invoice. + +But at the time of writing this, there is no CCK 3 version for Drupal 7. So, I +created the same thing using +[Field Collection](http://drupal.org/project/field_collection) and +[Entity](http://drupal.org/project/entity) modules. + +With the modules uploaded and enabled, go to admin/structure/field-collections +and create a field collection. + +With the module enabled, you can go to your content type and add a Field +Collection field. By default, the only available Widget type is 'Hidden'. + +Next, go to admin/structure/field-collections and add some fields to the field +collection - the same way that you would for a content type. For this collection +is going to contain two node reference fields - Image and Link. + +With the Field Collection created, I can now add it as a field within my content +type. + +Whilst this works perfectly, the field collection is not editable from the node +edit form. You need to load the node, and the collection is displayed here with +add, edit, and delete buttons. This wasn't an ideal solution, and I wanted to be +able to edit the fields within the collection from the node edit form - the same +way as I can using multigroups in Drupal 6. + +After some searching I found +[a link to a patch](http://drupal.org/node/977890#comment-4184524) which when +applied adds a 'subform' widget type to the field collection field and allows +for it to be embedded into, and editable from within the node form. Going back +to the content type fields page, and clicking on 'Hidden' (the name of the +current widget), I can change it to subform and save my changes. + +With this change applied, when I go back to add or edit a node within this +content type, my field collection will be easily editable directly within the +form. diff --git a/source/_posts/create-omega-subtheme-less-css-preprocessor-using-omega-tools-and-drush.md b/source/_posts/create-omega-subtheme-less-css-preprocessor-using-omega-tools-and-drush.md new file mode 100644 index 00000000..08634159 --- /dev/null +++ b/source/_posts/create-omega-subtheme-less-css-preprocessor-using-omega-tools-and-drush.md @@ -0,0 +1,62 @@ +--- +title: Create an Omega Subtheme with LESS CSS Preprocessor using Omega Tools and Drush +date: 2012-04-16 +excerpt: How to create an Omega subtheme on the command line using Drush. +tags: + - drupal + - drupal-7 + - drupal-planet + - less + - omega + - theming +--- + +In this tutorial I'll be showing how to create an +[Omega](http://drupal.org/project/omega) subtheme using the +[Omega Tools](http://drupal.org/project/omega_tools) module, and have it working +with the [LESS CSS preprocessor](http://lesscss.org). + +The first thing that I need to do is download the Omega theme and the Omega +Tools and [LESS](http://drupal.org/project/less 'LESS module on drupal.org') +modules, and then to enable both modules. I'm doing this using Drush, but you +can of course do this via the admin interface at admin/modules. + +```bash +$ drush dl less omega omega_tools; +$ drush en -y less omega_tools +``` + +With the Omega Tools module enabled I get the drush omega-subtheme command that +creates my Omega subtheme programatically. Using this command, I'm creating a +new subtheme, enabling it and setting it as the default theme on my site. + +```bash +$ drush omega-subtheme "Oliver Davies" --machine_name="oliverdavies" --enable --set-default +``` + +By default, four stylesheets are created within the subtheme's css directory. +The first thing that I'm going to do is rename `global.css` to `global.less`. + +```bash +$ mv css/global.css css/global.less +``` + +Now I need to find all references to global.css within my oliverdavies.info +file. I did this using `$ nano oliverdavies.info`, pressing `Ctrl+W` to search, +then `Ctrl+R` to replace, entering `global.css` as the search phrase, and then +`global.less` as the replacement text. After making any changes to +oliverdavies.info, I need to clear Drupal's caches for the changes to be +applied. + +```bash +$ drush cc all +``` + +I tested my changes by making some quick additions to my global.less file and +reloading the page. + +If your changes aren't applied, then confirm that your global.less file is +enabled within your theme's configuration. I did this by going to +admin/appearance/settings/oliverdavies, clicking on the Toggle styles tab within +_Layout configuration_ and finding global.less at the bottom of _Enable optional +stylesheets_. diff --git a/source/_posts/create-slideshow-multiple-images-using-fancy-slide.md b/source/_posts/create-slideshow-multiple-images-using-fancy-slide.md new file mode 100644 index 00000000..3ebe852c --- /dev/null +++ b/source/_posts/create-slideshow-multiple-images-using-fancy-slide.md @@ -0,0 +1,50 @@ +--- +title: Create a Slideshow of Multiple Images Using Fancy Slide +date: 2010-05-25 +excerpt: How to create a slideshow of images using Drupal’s Fancy Slide module. +tags: + - drupal + - drupal-6 + - drupal-planet + - fancy-slide + - slideshow +--- + +Whilst updating my About page, I thought about creating a slideshow of several +images instead of just the one static image. When I looking on Drupal.org, the +only slideshow modules were to create slideshows of images that were attached to +different nodes - not multiple images attached to one node. Then, I found the +[Fancy Slide](http://drupal.org/project/fancy_slide) module. It's a jQuery +Slideshow module with features that include integration with the +[CCK](http://drupal.org/project/cck), +[ImageCache](http://drupal.org/project/imagecache) and +[Nodequeue](http://drupal.org/project/nodequeue) modules. + +I added an CCK Image field to my Page content type, and set the number of values +to 3, then uploaded my images to the Page. + +Whilst updating my About page, I thought about creating a slideshow of several +images instead of just the one static image. When I looking on Drupal.org, the +only slideshow modules were to create slideshows of images that were attached to +different nodes - not multiple images attached to one node. Then, I found the +[Fancy Slide](http://drupal.org/project/fancy_slide) module. It's a jQuery +Slideshow module with features that include integration with the +[CCK](http://drupal.org/project/cck), +[ImageCache](http://drupal.org/project/imagecache) and +[Nodequeue](http://drupal.org/project/nodequeue) modules. Once the Images were +added, I went to the Fancy Slide settings page and created the slideshow. + +I added the dimensions of my images, the type of animation, specified the node +that contained the images, the slideshow field, delay between slides and +transition speed. With the slideshow created, it now needed embedding into the +page. + +I added the following code into my About page, as described in the Fancy Slide +readme.txt file - the number representing the ID of the slideshow. + +```php + +``` + +In my opinion, this adds a nice effect to the About page. I like it because it's +easy to set up, and easy to add additional images later on if required. diff --git a/source/_posts/create-virtual-hosts-mac-os-x-using-virtualhostx.md b/source/_posts/create-virtual-hosts-mac-os-x-using-virtualhostx.md new file mode 100644 index 00000000..017dfb16 --- /dev/null +++ b/source/_posts/create-virtual-hosts-mac-os-x-using-virtualhostx.md @@ -0,0 +1,50 @@ +--- +title: Create Virtual Hosts on Mac OS X Using VirtualHostX +date: 2010-07-02 +excerpt: + How to use the VirtualHostX application to manage virtual hosts on Mac OS X. +tags: + - drupal-6 + - drupal-planet + - mamp + - virtual-hosts + - virtualhostx +--- + +This isn't a Drupal related topic per se, but it is a walk-through of one of the +applications that I use whilst doing Drupal development work. I assume, like +most Mac OS X users, I use [MAMP](http://www.mamp.info/en/index.html) to run +Apache, MySQL and PHP locally whilst developing. I also use virtual hosts in +Apache to create local .dev domains which are as close as possible to the actual +live domains. For example, if I was developing a site called mysite.com, my +local development version would be mysite.dev. + +Normally, I would have to edit the hosts file and Apache's httpd.conf file to +create a virtual host. The first to set the domain and it's associated IP +address, and the other to configure the domain's directory, default index file +etc. However, using [VirtualHostX](http://clickontyler.com/virtualhostx), I can +quickly create a virtual host without having to edt any files. Enter the virtual +domain name, the local path and the port, and apply the settings. VirtualHostX +automatically restarts Apache, so the domain is ready to work straight away. You +can also enter custom directives from within the GUI. + +There's also an option to share the host over the local network. Next, I intend +on configuring a virtual Windows PC within VMware Fusion to view these domains +so that I can do cross-browser testing before putting a site live. + +I ensured that my Apache configuration within MAMP was set to port 80, and that +VirtualHostX was using Apache from MAMP instead of Apple's built-in Apache. + +**Note:** One problem that I had after setting this up, was that I was receving +an error when attempting to open a Drupal website which said _'No such file or +directory'._ + +After some troubleshooting, I found out that Web Sharing on my Mac had become +enabled (I don't know why, I've never enabled it), and that this was causing a +conflict with Apache. Once I opened my System Preferences and disabled it, +everything worked fine! + +This, along with [MAMP](http://www.mamp.info/en/index.html), +[Coda](http://www.panic.com/coda), [Sequel Pro](http://www.sequelpro.com), and +[Transmit](http://www.panic.com/transmit), has become an essential tool within +my development environment. diff --git a/source/_posts/create-zen-sub-theme-using-drush.md b/source/_posts/create-zen-sub-theme-using-drush.md new file mode 100644 index 00000000..ee7981e6 --- /dev/null +++ b/source/_posts/create-zen-sub-theme-using-drush.md @@ -0,0 +1,40 @@ +--- +title: Create a Zen Sub-theme Using Drush +date: 2013-09-06 +excerpt: How to quickly create a Zen sub-theme using Drush. +tags: + - drupal + - drupal-planet + - drush + - zen + - theming +--- + +How to use [Drush](https://drupal.org/project/drush) to quickly build a new +sub-theme of [Zen](https://drupal.org/project/zen). + +First, download the [Zen](https://drupal.org/project/zen 'The Zen theme') theme +if you haven't already done so. + +```bash +$ drush dl zen +``` + +This will now enable you to use the "drush zen" command. + +```bash +$ drush zen "Oliver Davies" oliverdavies --description="A Zen sub-theme for oliverdavies.co.uk" --without-rtl +``` + +The parameters that I'm passing it are: + +1. The human-readable name of the theme. +2. The machine-readable name of the theme. +3. The description of the theme (optional). +4. A flag telling Drush not to include any right-to-left elements within my + sub-theme as these aren't needed (optional). + +This will create a new theme in sites/all/themes/oliverdavies. + +For further help, type `$ drush help zen` to see the Drush help page for the zen +command. diff --git a/source/_posts/creating-custom-phpunit-command-ddev.md b/source/_posts/creating-custom-phpunit-command-ddev.md new file mode 100644 index 00000000..a1e6b964 --- /dev/null +++ b/source/_posts/creating-custom-phpunit-command-ddev.md @@ -0,0 +1,82 @@ +--- +title: Creating a custom PHPUnit command for DDEV +excerpt: How to create a custom command to run PHPUnit commands in DDEV. +tags: + - ddev + - drupal + - drupal-planet + - php +date: 2020-08-28 +--- + +To begin with, let's create an empty file for our command: + +```bash +touch .ddev/commands/web/phpunit +``` +Commands are located within the `.ddev/commands` directory, with a sub-directory for the container name in which the command should be executed - or `host` if it's a command that is to be run on the host machine. + +As [the example repo](https://github.com/opdavies/ddev-phpunit-command-example) has a `web` sub-directory to mimic my Drupal application structure, the command should be run inside the web container so the file should be placed within the `.ddev/commands/web` directory. + +As we want the command to be 'phpunit', the filename should also be `phpunit`. + +This is an example of a basic command, which is a simple bash script: + +```bash +#!/usr/bin/env bash + +echo 'running phpunit...' +``` + +To begin with, let's echo some simple text to check that the command is working. It should also be listed if you run the `ddev` command. + +To check the working directory that it used when the command is run, add the following line in the command file: + +```bash +echo $(pwd) +``` + +In the example, it is `/var/www/html/web`. Note that we are already inside the `web` sub-directory. + +## Running PHPUnit + +To run PHPUnit, I can add the following to the command file: + +``` +../vendor/bin/phpunit --config .. $* +``` + +As we're already in the `web` directory, the command needs to go up on level before running the PHPUnit command, and uses `--config` to define the path to the `phpunit.xml.dist` file which is also in the parent directory. + +Using `$*` adds any additional arguments from the CLI to the command inside the container. + +The command could be made simpler by overridding the `working_directory` value in `.ddev/config`: + +```json +working_dir: + web: /var/www/html +``` + +This means that we start in `/var/www/html` rather than inside the `web` directory, and that we can simplify the command to be: + +``` +vendor/bin/phpunit $* +``` + +Because the `phpunit.xml.dist` file is inside the working directory, I no longer need to specify its path. + +## Adding documentation + +To add documentation and help text to the command, add these lines to the command file: + +```bash +## Description: Run PHPUnit tests inside the web container. +## Usage: phpunit +## Example: "ddev phpunit" or with additional arguments such as "ddev phpunit --testdox" +``` + +These will be parsed and shown when someone runs `ddev phpunit -h`, and can be used to show various examples such as adding additional arguments for the PHPUnit command. + +With this all in place, we can run commands like `ddev phpunit` or `ddev phpunit --testdox`, or even `ddev phpunit modules/custom/opdavies_talks --filter=TalkEventDateTest` for a Drupal project, and have that command and tests running inside DDEV! + +For more information on DDEV and creating custom commands, see the [DDEV documentation](https://ddev.readthedocs.io/en/stable/users/extend/custom-commands). diff --git a/source/_posts/creating-custom-phpunit-command-docksal.md b/source/_posts/creating-custom-phpunit-command-docksal.md new file mode 100644 index 00000000..3caeeb3a --- /dev/null +++ b/source/_posts/creating-custom-phpunit-command-docksal.md @@ -0,0 +1,366 @@ +--- +title: Creating a Custom PHPUnit Command for Docksal +date: 2018-05-06 +excerpt: + How to write custom commands for Docksal, including one to easily run PHPUnit + tests in Drupal 8. +tags: + - docksal + - drupal + - drupal-8 + - drupal-planet + - phpunit + - testing +--- + +This week I’ve started writing some custom commands for my Drupal projects that +use Docksal, including one to easily run PHPUnit tests in Drupal 8. This is the +process of how I created this command. + +## What is Docksal? + +Docksal is a local Docker-based development environment for Drupal projects and +other frameworks and CMSes. It is our standard tool for local environments for +projects at [Microserve][0]. + +There was a [great talk][1] recently at Drupaldelphia about Docksal. + +## Why write a custom command? + +One of the things that Docksal offers (and is covered in the talk) is the +ability to add custom commands to the Docksal’s `fin` CLI, either globally or as +part of your project. + +As an advocate of automated testing and TDD practitioner, I write a lot of tests +and run PHPUnit numerous times a day. I’ve also given [talks][6] and have +[written other posts][7] on this site relating to testing in Drupal. + +There are a couple of ways to run PHPUnit with Docksal. The first is to use +`fin bash` to open a shell into the container, move into the docroot directory +if needed, and run the `phpunit` command. + +```bash +fin bash +cd /var/www/docroot +../vendor/bin/phpunit -c core modules/custom +``` + +Alternatively, it can be run from the host machine using `fin exec`. + +``` +cd docroot +fin exec '../vendor/bin/phpunit -c core modules/custom' +``` + +Both of these options require multiple steps as we need to be in the `docroot` +directory where the Drupal code is located before the command can be run, and +both have quite long commands to run PHPUnit itself - some of which is repeated +every time. + +By adding a custom command, I intend to: + +1. Make it easier to get set up to run PHPUnit tests - i.e. setting up a + `phpunit.xml` file. +1. Make it easier to run the tests that we’d written by shortening the command + and making it so it can be run anywhere within our project. + +I also hoped to make it project agnostic so that I could add it onto any project +and immediately run it. + +## Creating the command + +Each command is a file located within the `.docksal/commands` directory. The +filename is the name of the command (e.g. `phpunit`) with no file extension. + +To create the file, run this from the same directory where your `.docksal` +directory is: + +```bash +mkdir -p .docksal/commands +touch .docksal/commands/phpunit +``` + +This will create a new, empty `.docksal/commands/phpunit` file, and now the +`phpunit` command is now listed under "Custom commands" when we run `fin`. + +![](/images/blog/docksal-phpunit-command/1.gif) + +You can write commands with any interpreter. I’m going to use bash, so I’ll add +the shebang to the top of the file. + +```bash +#!/usr/bin/env bash +``` + +With this in place, I can now run `fin phpunit`, though there is no output +displayed or actions performed as the rest of the file is empty. + +## Adding a description and help text + +Currently the description for our command when we run `fin` is the default "No +description" text. I’d like to add something more relevant, so I’ll start by +adding a new description. + +fin interprets lines starting with `##` as documentation - the first of which it +uses as the description. + +```bash +#!/usr/bin/env bash + +## Run automated PHPUnit tests. +``` + +Now when I run it, I see the new description. + +![](/images/blog/docksal-phpunit-command/2.gif) + +Any additional lines are used as help text with running `fin help phpunit`. Here +I’ll add an example command to demonstrate how to run it as well as some more +in-depth text about what the command will do. + +```bash +#!/usr/bin/env bash + +## Run automated PHPUnit tests. +## +## Usage: fin phpunit +## +## If a core/phpunit.xml file does not exist, copy one from elsewhere. +## Then run the tests. +``` + +Now when I run `fin help phpunit`, I see the new help text. + +![](/images/blog/docksal-phpunit-command/3.gif) + +## Adding some content + +### Setting the target + +As I want the commands to be run within Docksal’s "cli" container, I can specify +that with `exec_target`. If one isn’t specified, the commands are run locally on +the host machine. + +``` +#: exec_target = cli +``` + +### Available variables + +These variables are provided by fin and are available to use within any custom +commands: + +- `PROJECT_ROOT` - The absolute path to the nearest `.docksal` directory. +- `DOCROOT` - name of the docroot folder. +- `VIRTUAL_HOST` - the virtual host name for the project. Such as + `myproject.docksal`. +- `DOCKER_RUNNING` - (string) "true" or "false". + +
+**Note:** If the `DOCROOT` variable is not defined within the cli container, ensure that it’s added to the environment variables in `.docksal/docksal.yml`. For example: + +``` +version: "2.1" + +services: + cli: + environment: + - DOCROOT +``` + +
+ +### Running phpunit + +When you run the `phpunit` command, there are number of options you can pass to +it such as `--filter`, `--testsuite` and `--group`, as well as the path to the +tests to execute, such as `modules/custom`. + +I wanted to still be able to do this by running `fin phpunit ` so the +commands can be customised when executed. However, as the first half of the +command (`../vendor/bin/phpunit -c core`) is consistent, I can wrap that within +my custom command and not need to type it every time. + +By using `"$@"` I can capture any additional arguments, such as the test +directory path, and append them to the command to execute. + +I’m using `$PROJECT_ROOT` to prefix the command with the absolute path to +`phpunit` so that I don’t need to be in that directory when I run the custom +command, and `$DOCROOT` to always enter the sub-directory where Drupal is +located. In this case, it’s "docroot" though I also use "web" and I’ve seen +various others used. + +```bash +DOCROOT_PATH="${PROJECT_ROOT}/${DOCROOT}" +DRUPAL_CORE_PATH="${DOCROOT_PATH}/core" + +# If there is no phpunit.xml file, copy one from elsewhere. + +# Otherwise run the tests. +${PROJECT_ROOT}/vendor/bin/phpunit -c ${DRUPAL_CORE_PATH} "$@" +``` + +For example, `fin phpunit modules/custom` would execute +`/var/www/vendor/bin/phpunit -c /var/www/docroot/core modules/custom` within the +container. + +I can then wrap this within a condition so that the tests are only run when a +`phpunit.xml` file exists, as it is required for them to run successfully. + +```bash +if [ ! -e ${DRUPAL_CORE_PATH}/phpunit.xml ]; then + # If there is no phpunit.xml file, copy one from elsewhere. +else + ${PROJECT_ROOT}/vendor/bin/phpunit -c ${DRUPAL_CORE_PATH} "$@" +fi +``` + +### Creating phpunit.xml - step 1 + +My first thought was that if a `phpunit.xml` file doesn’t exist was to duplicate +core’s `phpunit.xml.dist` file. However this isn’t enough to run the tests, as +values such as `SIMPLETEST_BASE_URL`, `SIMPLETEST_DB` and +`BROWSERTEST_OUTPUT_DIRECTORY` need to be populated. + +As the tests wouldn't run at this point, I’ve exited early and displayed a +message to the user to edit the new `phpunit.xml` file and run `fin phpunit` +again. + +```bash +if [ ! -e ${DRUPAL_CORE_PATH}/phpunit.xml ]; then + echo "Copying ${DRUPAL_CORE_PATH}/phpunit.xml.dist to ${DRUPAL_CORE_PATH}/phpunit.xml." + echo "Please edit it's values as needed and re-run 'fin phpunit'." + cp ${DRUPAL_CORE_PATH}/phpunit.xml.dist ${DRUPAL_CORE_PATH}/phpunit.xml + exit 1; +else + ${PROJECT_ROOT}/vendor/bin/phpunit -c ${DRUPAL_CORE_PATH} "$@" +fi +``` + +However this isn’t as streamlined as I originally wanted as it still requires +the user to perform an additional step before the tests can run. + +### Creating phpunit.xml - step 2 + +My second idea was to keep a pre-configured file within the project repository, +and to copy that into the expected location. That approach would mean that the +project specific values would already be populated, as well as any +customisations made to the default settings. I decided on +`.docksal/drupal/core/phpunit.xml` to be the potential location. + +Also, if this file is copied then we can go ahead and run the tests straight +away rather than needing to exit early. + +If a pre-configured file doesn’t exist, then we can default back to copying +`phpunit.xml.dist`. + +To avoid duplication, I created a reusable `run_tests()` function so it could be +executed in either scenario. + +```bash +run_tests() { + ${PROJECT_ROOT}/vendor/bin/phpunit -c ${DRUPAL_CORE_PATH} "$@" +} + +if [ ! -e ${DRUPAL_CORE_PATH}/phpunit.xml ]; then + if [ -e "${PROJECT_ROOT}/.docksal/drupal/core/phpunit.xml" ]; then + echo "Copying ${PROJECT_ROOT}/.docksal/drupal/core/phpunit.xml to ${DRUPAL_CORE_PATH}/phpunit.xml" + cp "${PROJECT_ROOT}/.docksal/drupal/core/phpunit.xml" ${DRUPAL_CORE_PATH}/phpunit.xml + run_tests "$@" + else + echo "Copying ${DRUPAL_CORE_PATH}/phpunit.xml.dist to ${DRUPAL_CORE_PATH}/phpunit.xml." + echo "Please edit it's values as needed and re-run 'fin phpunit'." + cp ${DRUPAL_CORE_PATH}/phpunit.xml.dist ${DRUPAL_CORE_PATH}/phpunit.xml + exit 1; + fi +else + run_tests "$@" +fi +``` + +This means that I can execute less steps and run a much shorter command compared +to the original, and even if someone didn’t have a `phpunit.xml` file created +they could have copied into place and have tests running with only one command. + +## The finished file + +```bash +#!/usr/bin/env bash + +#: exec_target = cli + +## Run automated PHPUnit tests. +## +## Usage: fin phpunit +## +## If a core/phpunit.xml file does not exist, one is copied from +## .docksal/core/phpunit.xml if that file exists, or copied from the default +## core/phpunit.xml.dist file. + +DOCROOT_PATH="${PROJECT_ROOT}/${DOCROOT}" +DRUPAL_CORE_PATH="${DOCROOT_PATH}/core" + +run_tests() { + ${PROJECT_ROOT}/vendor/bin/phpunit -c ${DRUPAL_CORE_PATH} "$@" +} + +if [ ! -e ${DRUPAL_CORE_PATH}/phpunit.xml ]; then + if [ -e "${PROJECT_ROOT}/.docksal/drupal/core/phpunit.xml" ]; then + echo "Copying ${PROJECT_ROOT}/.docksal/drupal/core/phpunit.xml to ${DRUPAL_CORE_PATH}/phpunit.xml" + cp "${PROJECT_ROOT}/.docksal/drupal/core/phpunit.xml" ${DRUPAL_CORE_PATH}/phpunit.xml + run_tests "$@" + else + echo "Copying phpunit.xml.dist to phpunit.xml" + echo "Please edit it's values as needed and re-run 'fin phpunit'." + cp ${DRUPAL_CORE_PATH}/phpunit.xml.dist ${DRUPAL_CORE_PATH}/phpunit.xml + exit 0; + fi +else + run_tests "$@" +fi +``` + +It’s currently available as a [GitHub Gist][2], though I’m planning on moving it +into a public GitHub repository either on my personal account or the [Microserve +organisation][3], for people to either use as examples or to download and use +directly. + +I’ve also started to add other commands to projects such as `config-export` to +standardise the way to export configuration from Drupal 8, run Drupal 7 tests +with SimpleTest, and compile front-end assets like CSS within custom themes. + +I think it’s a great way to shorten existing commands, or to group multiple +commands into one like in this case, and I can see a lot of other potential uses +for it during local development and continuous integration. Also being able to +run one command like `fin init` and have it set up everything for your project +is very convenient and a big time saver! + +
+Since writing this post, I’ve had a [pull request][8] accepted for this command to be added as a [Docksal add-on][9]. This means that the command can be added to any Docksal project by running `fin addon install phpunit`. It will be installed into the `.docksal/addons/phpunit` directory, and displayed under "Addons" rather than "Custom commands" when you run `fin`. +
+ +## Resources + +- [PHPUnit](https://phpunit.de) +- [PHPUnit in Drupal 8][4] +- [Main Docksal website](https://docksal.io) +- [Docksal documentation](https://docksal.readthedocs.io) +- [Docksal: one tool to rule local and CI/CD environments][1] - Docksal talk + from Drupaldelphia +- [phpcs example custom command][5] +- [phpunit command Gist][2] +- [Docksal addons blog post][9] +- [Docksal addons repository][10] + +[0]: {{site.companies.microserve.url}} +[1]: https://youtu.be/1sjsvnx1P7g +[2]: https://gist.github.com/opdavies/72611f198ffd2da13f363ea65264b2a5 +[3]: {{site.companies.microserve.github}} +[4]: https://www.drupal.org/docs/8/phpunit +[5]: + https://github.com/docksal/docksal/blob/develop/examples/.docksal/commands/phpcs +[6]: /talks/tdd-test-driven-drupal +[7]: /articles/tags/testing +[8]: https://github.com/docksal/addons/pull/15 +[9]: https://blog.docksal.io/installing-addons-in-a-docksal-project-172a6c2d8a5b +[10]: https://github.com/docksal/addons diff --git a/source/_posts/creating-local-and-staging-sites-drupals-domain-module-enabled.md b/source/_posts/creating-local-and-staging-sites-drupals-domain-module-enabled.md new file mode 100644 index 00000000..a016af6c --- /dev/null +++ b/source/_posts/creating-local-and-staging-sites-drupals-domain-module-enabled.md @@ -0,0 +1,52 @@ +--- +title: Creating Local and Staging sites with Drupal's Domain Module Enabled +date: 2013-07-17 +excerpt: How to use aliases within Domain module for pre-production sites. +tags: + - databases + - domain + - drupal + - drupal-planet + - table-prefixing +--- + +The +[Domain Access project](https://drupal.org/project/domain 'The Domain Access project on Drupal.org') +is a suite of modules that provide tools for running a group of affiliated sites +from one Drupal installation and a single shared database. The issue is that the +domains are stored within the database so these are copied across when the data +is migrated between environments, whereas the domains are obviously going to +change. + +Rather than changing the domain settings within the Domain module itself, the +best solution I think is to use table prefixes and create a different domain +table per environment. With a live, staging and local domains, the tables would +be named as follows: + +```bash +live_domain +local_domain +staging_domain +``` + +Within each site's settings.php file, define the prefix for the domain table +within the databases array so that each site is looking at the correct table for +its environment. + +```php +$databases['default']['default'] = array( + 'driver' => 'mysql', + 'database' => 'foobar', + 'username' => 'foo', + 'password' => 'bar', + 'host' => 'localhost', + 'prefix' => array( + 'default' => '', + 'domain' => 'local_', // This will use the local_domain table. + // Add any other prefixed tables here. + ), +); +``` + +Within each environment-specific domain table, update the subdomain column to +contain the appropriate domain names. diff --git a/source/_posts/creating-using-custom-tokens-drupal-7.md b/source/_posts/creating-using-custom-tokens-drupal-7.md new file mode 100644 index 00000000..978569f1 --- /dev/null +++ b/source/_posts/creating-using-custom-tokens-drupal-7.md @@ -0,0 +1,162 @@ +--- +title: Creating and using custom tokens in Drupal 7 +date: 2013-02-16 +excerpt: + This post outlines the steps required to create your own custom tokens in + Drupal. +tags: + - drupal + - drupal-7 + - drupal-planet + - tokens +--- + +This post outlines the steps required to create your own custom tokens in +Drupal. + +When writing the recent releases of the +[Copyright Block](http://drupal.org/project/copyright_block) module, I used +tokens to allow the user to edit and customise their copyright message and place +the copyright_message:dates token in the desired position. When the block is +rendered, the token is replaced by the necessary dates. + +We will be using the fictional _foo_ module to demonstrate this. + +## Requirements + +- [Token module](http://drupal.org/project/token) + +## Recommended + +- [Devel module](http://drupal.org/project/devel) - useful to run `dpm()` and + `kpr()` functions +- [Copyright Block module](http://drupal.org/project/copyright_block) - 7.x-2.x + and 6.x-1.x use tokens, handy as a reference + +## Implementing hook_token_info() + +The first thing that we need to do is define the new token type and/or the token +itself, along with it's descriptive text. To view the existing tokens and types, +use `dpm(token_get_info());`, assuming that you have the +[Devel module](http://drupal.org/project/devel) installed. + +```php +/** + * Implements hook_token_info(). + */ +function foo_token_info() { + $info = array(); + + // Add any new tokens. + $info['tokens']['foo']['bar'] = t('This is my new bar token within the foo type.'); + + // Return them. + return $info; +} +``` + +In this case, the token called _bar_ resides within the _foo_ group. + +If I needed to add a new token within an existing token type, such as 'node', +the syntax would be `$info['tokens']['node']['bar']`. + +## Implementing hook_tokens() + +Now that the Token module is aware of our new token, we now need to determine +what the token is replaced with. This is done using `hook_tokens()`. Here is the +basic code needed for an implementation: + +```php +/** + * Implements hook_tokens(). + */ +function foo_tokens($type, $tokens, array $data = array(), array $options = array()) { + $replacements = array(); + + // Code goes here... + + // Return the replacements. + return $replacements; +} +``` + +The first thing to check for is the type of token using an `if()` function, as +this could be an existing type like 'node', 'user' or 'site', or a custom token +type like 'foo'. Once we're sure that we're looking at the right type(s), we can +use `foreach ($tokens as $name => $original)` to loop through each of the +available tokens using a `switch()`. For each token, you can perform some logic +to work out the replacement text and then add it into the replacements array +using `$replacements[$original] = $new;`. + +```php +/** + * Implements hook_tokens(). + */ +function foo_tokens($type, $tokens, array $data = array(), array $options = array()) { + $replacements = array(); + + // The first thing that we're going to check for is the type of token - node, + // user etc... + if ($type == 'foo') { + // Loop through each of the available tokens. + foreach ($tokens as $name => $original) { + // Find the desired token by name + switch ($name) { + case 'bar': + $new = ''; + + // Work out the value of $new... + + // Add the new value into the replacements array. + $replacements[$original] = $new; + break; + } + } + } + + // Return the replacements. + return $replacements; +} +``` + +## Example + +An example from Copyright Block module: + +```php +/** + * Implements hook_tokens(). + */ +function copyright_block_tokens($type, $tokens, array $data = array(), array $options = array()) { + $replacements = array(); + + if ($type == 'copyright_statement') { + foreach ($tokens as $name => $original) { + switch ($name) { + case 'dates': + $start_year = variable_get('copyright_block_start_year', date('Y')); + $current_year = date('Y'); + + $replacements[$original] = $start_year < $current_year ? $start_year . '-' . $current_year : $start_year; + break; + } + } + } + + return $replacements; +} +``` + +## Using token_replace() + +With everything defined, all that we now need to do is pass some text through +the `token_replace()` function to replace it with the values defined within +`hook_token()`. + +```php +$a = t('Something'); +// This would use any token type - node, user etc. +$b = token_replace($a); +// This would only use foo tokens. +$c = token_replace($a, array('foo')); +``` diff --git a/source/_posts/croeso-php-south-wales.md b/source/_posts/croeso-php-south-wales.md new file mode 100644 index 00000000..89f938e6 --- /dev/null +++ b/source/_posts/croeso-php-south-wales.md @@ -0,0 +1,82 @@ +--- +title: Croeso PHP South Wales! +date: 2018-08-01 +excerpt: Last night was the first meetup of Cardiff’s PHP South Wales user group. +tags: + - php + - php-south-wales + - meetups +has_tweets: true +--- + +Last night was the first meetup of Cardiff’s [PHP South Wales user group][0]! It +was a great first event, and it was great to meet a lot of new people as well as +catch up some familiars within the 36 (according to meetup.com) attendees - +including some [PHP South West][9] regulars. + +Organised by Steve and Amy McDougall, it was held in Barclays’ [Eagle Lab][1] +which was a great space, and it was cool to be back in Brunel House having +worked in that building previously whilst at Appnovation. + +{% include 'tweet' with { + class: 'my-6', + data_cards: true, + content: '

Pretty cool being back in the centre of Cardiff. pic.twitter.com/kh7Oi2tPDD

— Oliver Davies (@opdavies) July 31, 2018', +} %} + +## Speakers + +[Rob Allen][2] was the main speaker, who gave an interesting talk and a brave +live demo on serverless PHP and OpenWhisk. I always enjoy watching Rob speak, +which I’ve done a number of times at different events, and it was great to be +able to chat for a while after the meetup too. + +{% include 'tweet' with { + class: 'my-6', + data_cards: true, + content: '

Great to see ⁦@akrabat⁩ speaking about serverless PHP at the first ⁦@phpSouthWales⁩ meetup. #php #phpc #cardiff pic.twitter.com/Q9YaQ6O1fB

— Oliver Davies (@opdavies) July 31, 2018', +} %} + +We also had a couple of lightning talks, starting with [Ismael Velasco][3] +giving an introduction to progressive web applications (PWAs). I can see some +potential uses for this on my current work project, and I look forward to seeing +the full talk soon). + +I gave an updated version of my [Tailwind CSS lightning talk][4], and enjoyed +being able to show some examples of new sites using Tailwind such as [Laravel +Nova][5], [Spatie][6]’s new website and PHP South Wales itself! + +{% include 'tweet' with { + class: 'my-6', + data_cards: true, + content: '

Lightning talk time, first @IsmaelVelasco talking about #PWA 😎🎉 pic.twitter.com/KrJGZlIp7V

— PHP South Wales (@phpSouthWales) July 31, 2018', +} %} + +## Conclusion + +It’s great to have a meetup in Cardiff again, and having thought about organsing +something myself previously, I’m glad to see someone step forward to do so. This +shows that there's still a strong PHP community in Cardiff and South Wales, and +hopefully this will be the first meetup of many. I’ll look forward to seeing the +local community grow! + +Thanks again to Steve and Amy for organising, Eagle Labs for hosting, the +sponsors, and Rob and Ismael for speaking. + +It would be great to see even more people at the next one. If you’re interested, +take a look at the [group’s website][0], [meetup.com group][7] and [Twitter +profile][8]. Alternatively, get in touch with myself or one of the organisers +for more information. + +**Croeso ac iechyd da PHP South Wales!** + +[0]: https://www.phpsouthwales.uk +[1]: https://labs.uk.barclays/locations/cardiff-en +[2]: https://twitter.com/akrabat +[3]: https://twitter.com/IsmaelVelasco +[4]: /talks/taking-flight-with-tailwind-css +[5]: https://nova.laravel.com +[6]: https://spatie.be +[7]: https://www.meetup.com/PHP-South-Wales +[8]: https://twitter.com/phpsouthwales +[9]: https://phpsw.uk diff --git a/source/_posts/debugging-drupal-commerce-illuminate-collections.md b/source/_posts/debugging-drupal-commerce-illuminate-collections.md new file mode 100644 index 00000000..6d94c045 --- /dev/null +++ b/source/_posts/debugging-drupal-commerce-illuminate-collections.md @@ -0,0 +1,140 @@ +--- +title: Debugging Drupal Commerce Promotions and Adjustments using Illuminate Collections (Drupal 8) +date: 2018-10-24 +excerpt: Using Laravel’s Illuminate Collections to debug an issue with a Drupal Commerce promotion. +tags: + - drupal + - drupal-8 + - drupal-commerce + - drupal-planet + - illuminate-collections + - laravel-collections + - php +promoted: true +--- + +Today I found another instance where I decided to use [Illuminate +Collections][0] within my Drupal 8 code; whilst I was debugging an issue where a +[Drupal Commerce][1] promotion was incorrectly being applied to an order. + +No adjustments were showing in the Drupal UI for that order, so after some +initial investigation and finding that `$order->getAdjustments()` was empty, I +determined that I would need to get the adjustments from each order item within +the order. + +If the order were an array, this is how it would be structured in this +situation: + +```php +$order = [ + 'id' => 1, + 'items' => [ + [ + 'id' => 1, + 'adjustments' => [ + ['name' => 'Adjustment 1'], + ['name' => 'Adjustment 2'], + ['name' => 'Adjustment 3'], + ] + ], + [ + 'id' => 2, + 'adjustments' => [ + ['name' => 'Adjustment 4'], + ] + ], + [ + 'id' => 3, + 'adjustments' => [ + ['name' => 'Adjustment 5'], + ['name' => 'Adjustment 6'], + ] + ], + ], +]; +``` + +## Getting the order items + +I started by using `$order->getItems()` to load the order’s items, converted +them into a Collection, and used the Collection’s `pipe()` method and the +`dump()` function provided by the [Devel module][2] to output the order items. + +```php +collect($order->getItems()) + ->pipe(function (Collection $collection) { + dump($collection); + }); +``` + +## Get the order item adjustments + +Now we have a Collection of order items, for each item we need to get it’s +adjustments. We can do this with `map()`, then call `getAdjustments()` on the +order item. + +This would return a Collection of arrays, with each array containing it’s own +adjustments, so we can use `flatten()` to collapse all the adjustments into one +single-dimensional array. + +```php +collect($order->getItems()) + ->map(function (OrderItem $order_item) { + return $order_item->getAdjustments(); + }) + ->flatten(1); +``` + +There are a couple of refactors that we can do here though: + +- Use `flatMap()` to combine the `flatten()` and `map()` methods. +- Use [higher order messages][3] to delegate straight to the `getAdjustments()` + method on the order, rather than having to create a closure and call the + method within it. + +```php +collect($order->getItems()) + ->flatMap->getAdjustments(); +``` + +## Filtering + +In this scenario, each order item had three adjustments - the correct promotion, +the incorrect one and the standard VAT addition. I wasn’t concerned about the +VAT adjustment for debugging, so I used `filter()` to remove it based on the +result of the adjustment’s `getSourceId()` method. + +```php +collect($order->getItems()) + ->flatMap->getAdjustments() + ->filter(function (Adjustment $adjustment) { + return $adjustment->getSourceId() != 'vat'; + }); +``` + +## Conclusion + +Now I have just the relevant adjustments, I want to be able to load each one to +load it and check it’s conditions. To do this, I need just the source IDs. + +Again, I can use a higher order message to directly call `getSourceId()` on the +adjustment and return it’s value to `map()`. + +```php +collect($order->getItems()) + ->flatMap->getAdjustments() + ->filter(function (Adjustment $adjustment) { + return $adjustment->getSourceId() != 'vat'; + }) + ->map->getSourceId(); +``` + +This returns a Collection containing just the relevant promotion IDs being +applied to the order that I can use for debugging. + +Now just to find out why the incorrect promotion was applying! + +[0]: https://laravel.com/docs/collections +[1]: https://drupalcommerce.org +[2]: https://www.drupal.org/project/devel +[3]: https://laravel-news.com/higher-order-messaging diff --git a/source/_posts/debugging-php-docker-xdebug-neovim-dap.md b/source/_posts/debugging-php-docker-xdebug-neovim-dap.md new file mode 100755 index 00000000..a6a0fe3b --- /dev/null +++ b/source/_posts/debugging-php-docker-xdebug-neovim-dap.md @@ -0,0 +1,102 @@ +--- +title: Debugging PHP in Docker with Xdebug, Neovim and DAP +date: ~ +tags: + - docker + - neovim + - dap + - xdebug + - php + - drupal +draft: true +--- + +I've been a full-time Neovim user for a year at the time of writing this post and whilst I was a semi-regular Xdebug user, it's something that I've managed to work around and have mostly resorted to `var_dump()`, `dump()`, or `dd()` instead for debugging. + +This week though, whilst working on some particularly tricky PHP code, I decided to spend some time and get Xdebug working and be able to use a step debugger within Neovim. + +https://gist.githubusercontent.com/opdavies/688a3c8917893bf34a3da32ff69c1837/raw/112e16634930d312cd04c525de42a198c8a32bb9/dap.lua + +## Installing Xdebug + +Installing Xdebug itself within Docker was straight forward. I was able to add two lines to my existing `RUN` command - `pecl install xdebug` to install the extension and `docker-php-ext-enable xdebug` to enable it. + +Now when I run `php -v` inside my container, I can see that it mentions Xdebug. + +## Configuring Xdebug + +https://www.youtube.com/watch?v=ZIGdBSD6zvU + +``` +xdebug.mode=develop,debug +xdebug.client_host=host.docker.internal +xdebug.discover_client_host=0 +xdebug.output_dir=/tmp/xdebug +xdebug.log=/tmp/xdebug/xdebug-example.log +xdebug.start_with_request=yes +``` +## Installing DAP plugins + +I use [Packer](https://github.com/wbthomason/packer.nvim) for managing my Neovim plugins so I needed to install some additional ones to add the DAP (debug adapter protocol) functionality. + +```lua +use "mfussenegger/nvim-dap" +use "rcarriga/nvim-dap-ui" +use "theHamsta/nvim-dap-virtual-text" +use "nvim-telescope/telescope-dap.nvim" +``` + +## Installing DAP dependencies + +[https://github.com/mfussenegger/nvim-dap/wiki/Debug-Adapter-installation#PHP](https://github.com/mfussenegger/nvim-dap/wiki/Debug-Adapter-installation#PHP) + +There's also a prerequisite for install the `vscode-php-debug` adapter. + +I configure my laptop with Ansible, so I added a new `debugger` role that is responsible for cloning this repository and installing its contents: + +[https://github.com/opdavies/dotfiles/blob/7681c535269049556736f1f857c8c9fd800857a3/roles/debugger/tasks/php.yaml](https://github.com/opdavies/dotfiles/blob/7681c535269049556736f1f857c8c9fd800857a3/roles/debugger/tasks/php.yaml) + +## Configuring DAP for Xdebug + +```lua +dap.adapters.php = { + type = "executable", + command = "node", + args = { os.getenv("HOME") .. "/build/vscode-php-debug/out/phpDebug.js" } +} + +dap.configurations.php = { + { + type = "php", + request = "launch", + name = "Listen for Xdebug", + port = 9003, + pathMappings = { + ["/var/www/html"] = "${workspaceFolder}" + } + } +} +``` + +I first needed to configure the adapter to use `vscode-php-debug` and then add a DAP configuration. + +The default port for the step debugger is now 9003 rather than 9000 so I changed this from the default, and as I'm working with PHP inside a container, I also added a path mapping so that my code could be found. + +## Testing the connection + +> [Step Debug] Creating socket for 'host.docker.internal:9003', getaddrinfo: Invalid argument. + +```yaml +services: + php: + volumes: + - "/tmp/xdebug:/tmp/xdebug" + extra_hosts: + - "host.docker.internal:host-gateway" +``` + +--- + +keymaps: + +https://github.com/opdavies/docker-drupal-example diff --git a/source/_posts/decorating-entity-metadata-wrapper-add-refactor-methods.md b/source/_posts/decorating-entity-metadata-wrapper-add-refactor-methods.md new file mode 100644 index 00000000..2ef5cd52 --- /dev/null +++ b/source/_posts/decorating-entity-metadata-wrapper-add-refactor-methods.md @@ -0,0 +1,141 @@ +--- +title: Decorating an Entity Metadata Wrapper to add and refactor methods +excerpt: How to use the Decorator design pattern with Drupal 7's EntityMetadataWrapper to extend it, and add and refactor custom methods. +tags: + - drupal + - drupal-7 + - drupal-planet + - php +date: 2021-02-24 +--- + +Following [yesterday's Entity Metadata Wrapper blog post](/blog/cleanly-retrieving-user-profile-data-using-entity-metadata-wrapper) and as I continued to work on this task, I noticed some duplication and found that I was repeating several of the same chaining steps in different methods in the same file. For example: + +```php +public function getFirstName(): string { + return $this + ->get('profile_user_basic') // Get the pupil's profile. + ->get('field_first_name') + ->value(); +} + +private function getTeacherFirstName(): string { + $this + ->get('profile_student') // Get the pupil's profile. + ->get('field_class') // Get the pupil's class. + ->get('field_teacher') // Get the class' teacher. + ->get('profile_user_basic') // Get the teacher's profile. + ->get('field_first_name') + ->value(); +} +``` + +In both cases, the last three lines are the same, where the same profile type is loaded, and the value is loaded from a field. + +I wanted to find a way to remove this duplication whilst also making the code more readable. Ideally, this would mean adding a method like `getFirstNameFromBasicProfile()` that would group the last three steps. + +## Extending the EntityDrupalWrapper + +I've done this before, where I've created a custom wrapper class with its own methods and extends `EntityDrupalWrapper`. This is how that might look: + +```php +final class PupilWrapper extends \EntityDrupalWrapper { + + public function __construct(\stdClass $data, $info = []) { + parent::__construct('user', $data, $info); + } + + public function getFirstName(): string { + return $this->getFirstNameFromBasicProfile(); + } + + public function getTeacherFirstName(): string { + return $this + ->get('profile_student') + ->get('field_class') + ->get('field_teacher') + ->getFirstNameFromBasicProfile(); + } + + private function getFirstNameFromBasicProfile(): string { + return $this + ->get('profile_user_basic') + ->get('field_first_name') + ->value(); + } + +} +``` + +Whilst this has worked in previous situations, this time I had this error: + +> Error: Call to undefined method EntityDrupalWrapper::getFirstNameFromBasicProfile() in Drupal\my_module\EntityWrapper\PupilWrapper->getTeacherFirstName + +This is because the `get()` method is returning an instance of `EntityStructureWrapper` (another class that extends `EntityDrupalWrapper`) which means that `getFirstNameFromBasicProfile()` is not accessible though it's in the same file. + +I tried overridding the `get()` method but wasn't able to get this to work. + +## Decorating the EntityDrupalWrapper + +Another option that I tried was to follow the Decorator design pattern, and add a new class that takes an `EntityDrupalWrapper` as an argument as uses it internally but doesn't extend it. Here's an example: + +```php +final class PupilWrapper { + + private $accountWrapper; + + public function __construct(\EntityMetadataWrapper $accountWrapper) { + $this->accountWrapper = $accountWrapper; + } + + public function getFirstName(): string { + return $this->getFirstNameFromBasicProfile(); + } + + public function getTeacherFirstName(): string { + return $this + ->get('profile_student') + ->get('field_class') + ->get('field_teacher') + ->getFirstNameFromBasicProfile(); + } + + private function getFirstNameFromBasicProfile(): string { + return $this + ->get('profile_user_basic') + ->get('field_first_name') + ->value(); + } + +} +``` + +In this case, the constructor argument is an instance of `EntityMetadataWrapper` so that it could be either an `EntityDrupalWrapper` or `EntityStructureWrapper`. + +### Re-adding required wrapper methods + +As the `get()` method is missing, this would cause an error: + +> Error: Call to undefined method Drupal\my_module\EntityWrapper\PupilWrapper::get() in Drupal\my_module\EntityWrapper\PupilWrapper->getFirstName() + +However, we can re-add it, have it get the value from `accountWrapper` and return another instance of `PupilWrapper` so that `getFirstNameFromBasicProfile()` will be available. + +```php +public function get(string $property): self { + return new self($this->accountWrapper->get($property)); +} +``` + +The `value()` method is also required, but this can delegate to the decorated wrapper: + +> Error: Call to undefined method Drupal\my_module\EntityWrapper\PupilWrapper::value() in Drupal\my_module\EntityWrapper\PupilWrapper->getFirstName() + +```php +public function value(): string { + return $this->accountWrapper->value(); +} +``` + +## Conclusion + +This was the first time that I tried extending Drupal 7's entity metadata wrappers in this way, but it worked well, removes the duplication and cleans up the code further. diff --git a/source/_posts/display-custom-menu-drupal-7-theme-template-file.md b/source/_posts/display-custom-menu-drupal-7-theme-template-file.md new file mode 100644 index 00000000..092916fd --- /dev/null +++ b/source/_posts/display-custom-menu-drupal-7-theme-template-file.md @@ -0,0 +1,27 @@ +--- +title: Display a Custom Menu in a Drupal 7 Theme Template File +date: 2012-08-18 +excerpt: The code needed to display a menu in a Drupal 7 template file. +tags: + - aria + - drupal + - drupal-7 + - drupal-planet + - php +--- + +For reference, this is the code needed to display a menu in a Drupal 7 template +file, including the navigation ARIA role. + +```php +$menu_name = 'menu-footer-menu'; +$menu_id = 'footer-menu'; +print theme('links', array( + 'links' => menu_navigation_links($menu_name), + 'attributes' => array( + 'id' => $menu_id, + 'role' => 'navigation', + 'class'=> array('links', 'inline') + ) +)); +``` diff --git a/source/_posts/display-git-branch-or-tag-names-your-bash-prompt.md b/source/_posts/display-git-branch-or-tag-names-your-bash-prompt.md new file mode 100644 index 00000000..0403bdfa --- /dev/null +++ b/source/_posts/display-git-branch-or-tag-names-your-bash-prompt.md @@ -0,0 +1,67 @@ +--- +title: Display Git Branch or Tag Names in your Bash Prompt +date: 2013-04-27 +excerpt: Whilst watching Drupalize.me's recent Introduction to Git series, I thought it was useful the way that the current Git branch or tag name was displayed in the bash prompt. Here's how to do it. +tags: + - drupal + - drupal-planet + - git + - terminal +--- + +Whilst watching [Drupalize.me](http://drupalize.me 'Drupalize.me')'s recent +[Introduction to Git series](http://drupalize.me/series/introduction-git-series 'Introduction to Git on Drupalize.me'), +I thought it was useful the way that the current Git branch or tag name was +displayed in the bash prompt. + +Here's how to do it. + +For example (with some slight modifications): + +```bash +oliver@oliver-mbp:~/Development/drupal(master) $ +oliver@oliver-mbp:~/Development/a11y_checklist(7.x-1.0) $ +``` + +Here's how to do it. + +To begin with, create a new file to contain the functions, + +```bash +vim ~/.bash/git-prompt +``` + +Paste the following code into the file, and save it. + +```bash +parse_git_branch () { + git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' +} + +parse_git_tag () { + git describe --tags 2> /dev/null +} + +parse_git_branch_or_tag() { + local OUT="$(parse_git_branch)" + if [ "$OUT" == " ((no branch))" ]; then + OUT="($(parse_git_tag))"; + fi + echo $OUT +} +``` + +Edit your `.bashrc` or `.bash_profile` file to override the PS1 value. + +```bash +vim ~/.bashrc +``` + +Add the following code at the bottom of the file, and save it. + +```bash +source ~/.bash/git-prompt +PS1="\u@\h:\w\$(parse_git_branch_or_tag) $ " +``` + +Restart your Terminal or type `source ~/.bashrc` to see your changes. diff --git a/source/_posts/display-number-facebook-fans-php.md b/source/_posts/display-number-facebook-fans-php.md new file mode 100644 index 00000000..fcf28c28 --- /dev/null +++ b/source/_posts/display-number-facebook-fans-php.md @@ -0,0 +1,30 @@ +--- +title: Display the Number of Facebook fans in PHP +date: 2011-03-15 +excerpt: How to use PHP to display the number of fans of a Facebook page. +tags: + - php +--- + +Replace the \$page_id value with your Page ID number (unless you want to show +the number of fans for this site).You can find your Page ID by logging into your +Facebook account, going to 'Adverts and Pages', clicking 'Edit page', and +looking at the URL. + +For example, mine is +. + +I've also wrapped the output in a number_format() function so that it properly +formatted with commas etc - like where I've used it within the +[Gold Event listing](http://www.horseandcountry.tv/events/paid) on the Horse & +Country TV website. + +```php +$page_id = "143394365692197"; +$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot"); +$fans = $xml->page->fan_count; +print number_format($fans); +``` + +This code was originally found at +. diff --git a/source/_posts/dividing-drupals-process-and-preprocess-functions-separate-files.md b/source/_posts/dividing-drupals-process-and-preprocess-functions-separate-files.md new file mode 100644 index 00000000..3e8fec99 --- /dev/null +++ b/source/_posts/dividing-drupals-process-and-preprocess-functions-separate-files.md @@ -0,0 +1,93 @@ +--- +title: Dividing Drupal's process and preprocess functions into separate files +date: 2012-05-24 +excerpt: If you use a lot of process and preprocess functions within your Drupal theme, then your template.php can get very long and it can become difficult to find a certain piece of code. Following the example of the Omega theme, I've started separating my process and preprocess functions into their own files. +tags: + - code + - drupal + - preprocessing + - theming +--- + +If you use a lot of process and preprocess functions within your Drupal theme, +then your template.php can get very long and it can become difficult to find a +certain piece of code. Following the example of the +[Omega theme](http://drupal.org/project/omega 'The Omega theme on Drupal.org'), +I've started separating my process and preprocess functions into their own +files. For example, mytheme_preprocess_node can be placed within a +preprocess/node.inc file, and mytheme_process_page can be placed within +process/page.inc. + +The first step is to use the default mytheme_process() and mytheme_preprocess() +functions to utilise my custom function. So within my template.php file: + +```php + This new version makes Media module available for all, improves migrations +> significantly, stabilizes the Content Moderation and Settings Tray modules, +> serves dynamic pages faster with BigPipe enabled by default, and introduces a +> new experimental entity layout user interface. The release includes several +> very important fixes for workflows of content translations and supports +> running on PHP 7.2. + +I’ve been very impressed by the new release cycle Drupal 8 and the usage of +semantic versioning. Though it adds a greater maintenance overhead for module, +theme, installation profile and distribution developers to ensure that our +projects are still working properly, having the ability to add new modules into +Drupal core as well as new installation profiles like the [Unami demonstration +profile][2] is pretty cool! + +For example, in addition to Unami, 8.5 alone adds media in core, two +experimental modules have been marked as stable, an experimental new layout +builder has been added and lots of PHP 7.2 improvements have been committed to +make 8.5 fully PHP 7.2 compatible. + +I’m already looking forward to see what’s coming in 8.6 later this year! + +For more information on the 8.5 release, see the [blog post on Drupal.org][1]. + +[0]: https://dri.es/drupal-8-5-0-released +[1]: https://www.drupal.org/blog/drupal-8-5-0 +[2]: + https://www.drupal.org/docs/8/umami-drupal-8-demonstration-installation-profile diff --git a/source/_posts/drupal-8-commerce-fixing-error-on-user-checkout.md b/source/_posts/drupal-8-commerce-fixing-error-on-user-checkout.md new file mode 100644 index 00000000..f7fa2212 --- /dev/null +++ b/source/_posts/drupal-8-commerce-fixing-error-on-user-checkout.md @@ -0,0 +1,95 @@ +--- +title: "Drupal 8 Commerce: Fixing 'No Such Customer' error on checkout" +date: 2018-08-15 +excerpt: Fixing a Drupal Commerce error when a user tries to complete a checkout. +tags: + - drupal + - drupal-8 + - drupal-commerce + - stripe +--- + +Recently I was experiencing an issue on the Drupal 8 website I’m working on, +where a small number of users were not able to complete the checkout process and +instead got a generic `The site has encountered an unexpected error` message. + +Looking at the log, I was able to see the error being thrown (the customer ID +has been redacted): + +> Stripe\Error\InvalidRequest: No such customer: cus_xxxxxxxxxxxxxx in +> Stripe\ApiRequestor::\_specificAPIError() (line 124 of +> /var/www/vendor/stripe/stripe-php/lib/ApiRequestor.php). + +Logging in to the Stripe account, I was able to confirm that the specified +customer ID did not exist. So where was it coming from, and why was Drupal +trying to retrieve a non-existent customer? + +## Investigation + +After some investigation, I found a table in the database named +`user__commerce_remote_id` which stores the remote customer ID for each payment +method (again, the customer ID has been redacted). + +![A screenshot of a row in the user__commerce_remote_id table](/images/blog/commerce-stripe-error/remote-id-table.png){.border.p-1} + +The `entity_id` and `revision_id` values in this case refer to the user that the +Stripe customer has been associated with. + +As there was no customer in Stripe with this ID, I think that this must be a +customer ID from the test environment (the data from which was deleted before +the site went live). + +### Drupal code + +This I believe is the Drupal code where the error was being triggered: + +```php +// modules/contrib/commerce_stripe/src/Plugin/Commerce/PaymentGateway/Stripe.php + +public function createPayment(PaymentInterface $payment, $capture = TRUE) { + ... + + $owner = $payment_method->getOwner(); + if ($owner && $owner->isAuthenticated()) { + $transaction_data['customer'] = $this->getRemoteCustomerId($owner); + } + + try { + $result = \Stripe\Charge::create($transaction_data); + ErrorHelper::handleErrors($result); + } + catch (\Stripe\Error\Base $e) { + ErrorHelper::handleException($e); + } + + ... +} +``` + +### Stripe code + +I can also see in the Stripe library where the original error is generated. + +```php +private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData) +{ + $msg = isset($errorData['message']) ? $errorData['message'] : null; + $param = isset($errorData['param']) ? $errorData['param'] : null; + $code = isset($errorData['code']) ? $errorData['code'] : null; + + switch ($rcode) { + ... + + case 404: + return new Error\InvalidRequest($msg, $param, $rcode, $rbody, $resp, $rheaders); + + ... + } +} +``` + +## Solution + +After confirming that it was the correct user ID, simply removing that row from +the database allowed the new Stripe customer to be created and for the user to +check out successfully. diff --git a/source/_posts/drupal-association.md b/source/_posts/drupal-association.md new file mode 100644 index 00000000..49805088 --- /dev/null +++ b/source/_posts/drupal-association.md @@ -0,0 +1,37 @@ +--- +title: Drupal Association +date: 2014-05-03 +excerpt: Next week, I'll be working for the Drupal Association. +tags: + - drupal + - personal +--- + +Today was my last day working at [Precedent](http://www.precedent.com). Next +week, I'll be starting my +[new job](https://assoc.drupal.org/node/18923 'Drupal.org Developer') at the +[Drupal Association](http://assoc.drupal.org) working on Drupal's home - +[Drupal.org](http://www.drupal.org). + +I was at Precedent for just over a year and had the opportunity to work on +several Drupal projects from project leading to ad-hoc module and theme +development, including my largest Drupal build to date. + +I was also lucky enough to go to +[DrupalCon Prague](http://prague2013.drupal.org) as well as +[DrupalCamp London](http://2014.drupalcamplondon.co.uk). + +I was able to [contribute some code](https://drupal.org/project/eventsforce) +back into the community and encourage other team members to do the same. + +It was good to be able to introduce some new tools like +[Vagrant](http://www.vagrantup.com), [Puppet](http://www.puppetlabs.com), +[SASS](http://www.sass-lang.com) and [Compass](http://www.compass-style.org) +into the team. I was pleased to introduce and champion the +[Git Flow](http://danielkummer.github.io/git-flow-cheatsheet 'Git Flow Cheat Sheet') +branching model, which them became the standard approach for all Drupal +projects, and hopefully soon all development projects. + +Working for the Drupal Association and on Drupal.org was an opportunity that I +couldn't refuse, and is certainly going to be a fun and interesting challenge. I +can't wait to get started! diff --git a/source/_posts/drupal-automated-testing-workshop-notes.md b/source/_posts/drupal-automated-testing-workshop-notes.md new file mode 100644 index 00000000..18163f3a --- /dev/null +++ b/source/_posts/drupal-automated-testing-workshop-notes.md @@ -0,0 +1,14 @@ +--- +title: Drupal automated testing workshop notes +excerpt: If you attended my automated testing with Drupal workshop this weekend, here are the links. +tags: + - drupal +date: 2020-11-15 +--- + +If you attended my automated testing and test driven development workshop this weekend at DrupalCamp NYC, or at DrupalCamp London in March, [here are the notes][notes] that we went through during the session. + +There is also [a separate code repository][code] that contains the example code, broken down commit by commit, and uses GitHub Actions to run the tests automatically on each push. + +[code]: https://github.com/opdavies/workshop-drupal-automated-testing-code +[notes]: https://github.com/opdavies/workshop-drupal-automated-testing diff --git a/source/_posts/drupal-body-classes-tailwind-css.md b/source/_posts/drupal-body-classes-tailwind-css.md new file mode 100644 index 00000000..e7e15c99 --- /dev/null +++ b/source/_posts/drupal-body-classes-tailwind-css.md @@ -0,0 +1,153 @@ +--- +title: Exporting Drupal body classes to use with Tailwind CSS +excerpt: How I've exported content from Drupal's body fields so they aren't missed by Tailwind's JIT mode or PurgeCSS. +date: 2022-07-02 +tags: + - drupal + - tailwind-css +--- + +I was recently [asked a question](https://www.drupal.org/project/tailwindcss/issues/3271487) in the issue queue for my [Tailwind starter kit Drupal theme](https://www.drupal.org/project/tailwindcss), about how to use classes within content with Tailwind CSS. + +The 5.x version of the theme has the JIT (just in time) compiler enabled by default and whilst it can work using Twig files in your theme, it doesn't know about classes used within content that is stored within the database. + +This is something that I've needed to solve in some of my own projects before too so there are a few options but I'd not recommend turning off the JIT compiler or PurgeCSS. + +## Adding classes to a safelist + +The first option is to use the `safelist` option within the `tailwind.config.js` file: + +```js +module.exports = { + content: [ + './templates/**/*.html.twig' + ], + safelist: [ + 'bg-red-500', + 'text-3xl', + 'lg:text-4xl', + ] +} +``` + +Adding any classes to the safelist will force them to be generated, or prevent them from being purged, even if they are not found within the theme's templates files. + +This is refered to within the Tailwind CSS documentation for [safelisting classes](https://tailwindcss.com/docs/content-configuration#safelisting-classes): + +> One example of where this can be useful is if your site displays user-generated content and you want users to be able to use a constrained set of Tailwind classes in their content that might not exist in your own site’s source files. + +## Extracting the safelist to a file + +In some projects, I found that I was adding a lot of classes to the safelist so I extracted the classes into a file instead. + +Whilst it could be a JavaScript object that could be imported, as long as Tailwind sees the classes being used, the files just need to exist in a file that can be scanned - even just a plain text file called `safelist.txt`: + +``` +bg-red-500 +text-3xl +lg:text-4xl +``` + +Rather than using the `safelist`, I can add the safelist file to `content` instead: + +```js +module.exports = { + content: [ + './safelist.txt', + './templates/**/*.html.twig' + ] +} +``` + +## Creating a safelist file automatically with Drush + +What we could also do is create the safelist file automatically based on the contents of the database using a custom Drush command. + +### Creating the command + +This can be done by creating a new PHP class within a custom module and use the `@command` annotation to specify the command to run: + +```php +database = $database; +} +``` + +### Completing the handle method + +As well as the database, I've added some properties to contain the table names to query as well as the name of the file to output: + +```php +private static array $tableNames = [ + 'block_content__body', + 'node__body', +]; + +private string $filename = 'safelist.txt'; +``` + +Within the `handle()` method, I'm using an [Illuminate Collection](/talks/using-illuminate-collections-outside-laravel) to loop over the array of tables, query the database, export the values, and write them into the file: + +```php +public function handle(): void { + $values = collect(self::$tableNames) + ->flatMap(fn(string $tableName) => + $this->getValuesFromTable($tableName)) + ->implode(PHP_EOL); + + file_put_contents($this->getFilePath(), $values); +} + +private function getFilePath(): string { + return drupal_get_path('theme', 'opdavies') . DIRECTORY_SEPARATOR + . $this->filename; +} + +private function getValuesFromTable(string $tableName): array { + return $this->database->select($tableName) + ->fields($tableName, ['body_value']) + ->execute() + ->fetchCol(); +} +``` + +Now, when Tailwind CSS is run, it will find the exported body contents within the safelist file, and ensure that the appropriate classes are generated. diff --git a/source/_posts/drupal-bristol-testing-workshop.md b/source/_posts/drupal-bristol-testing-workshop.md new file mode 100644 index 00000000..038f2f18 --- /dev/null +++ b/source/_posts/drupal-bristol-testing-workshop.md @@ -0,0 +1,112 @@ +--- +title: Drupal Bristol Testing Workshop +date: 2018-06-28 +excerpt: Yesterday evening, I did my first workshop, held at the Drupal Bristol user group. +tags: + - composer + - docksal + - drupal + - drupal-8 + - drupal-bristol + - php + - phpunit + - testing +--- + +Yesterday evening, I did [my first workshop][16] (and I believe, the first +workshop) held at the [{{ site.events['drupal_bristol'].name }}][14] user group. +The subject was automated testing with PHPUnit in Drupal 8, in preparation for +my talk at [{{ site.events['drupal_dev_days_18'].name }}][12] next week and to +help process some ideas for my [testing book][15]. + +Here are some details about what we covered, and some of my thoughts in review. + +## Local Environment + +Before the meetup, I set up a [repository on GitHub][0] that contains a +Composer-based Drupal 8 installation, based on the [Drupal 8 Composer +template][4] along with the [Examples module][5] (which includes some PHPUnit +tests) with a pre-configured [Docksal][2] environment to use locally - Docksal +being our standard local development environment that we use at +{{ site.companies['microserve'].name }} for all of our projects, so something +that I’m familiar with using. + +In addition to the default stack, I added [the PHPUnit add-on that I wrote][6] +so that it was easier to run tests, [configured settings.php using environment +variables][7] and added a custom `fin init` command to install the Composer +dependencies and install Drupal. This meant after that installing Docksal, +everyone had a running Drupal 8 website after only running `git clone` and +`fin init`, and could then run tests straight away using +`fin phpunit web/modules/contrib/examples/phpunit_example`. + +## Exercises + +Once everyone was set up, we moved on to talk about why testing is important and +the different options available to run them, before looking at the different +types of tests available in Drupal 8. For each test type, I explained what it +was used for and everyone completed an exercise on each - creating a test of +that type, initially seeing it fail, and then doing the work to get it to pass. + +The completed code that I wrote beforehand for these is available in their own +[GitHub repository][8], including all of the tests as well as the implementation +code. + +Once these exercises were completed, we looked at creating a blog page using +test driven development - the example that I use in the [TDD - Test-Driven +Drupal talk][9], to give a more real-word scenario. It would have been good to +have gone through this as an exercise too, if we’d have had more time. + +## Wrap Up + +To finish, I demonstrated the PHPUnit integration within PHPStorm (which is +working with Docksal) and showed some of the tests that I wrote for the [Private +Message Queue][10] and [System User][11] modules, to see how things like adding +items to queues and processing them, ensuring that emails are sent, to the right +users and contain the right data, can be tested, as well as some of the tests +that we’ve written on my work project over the last few months. + +## Slides + +I didn’t record this workshop, but I have exported the slides and embedded them +below: + +{% include 'talk/slides' with { + speakerdeck: { + id: '2679401cb2ad421789d372cb8d38e368', + ratio: '1.77777777777778', + } +} %} + +## Thoughts + +I was very happy with how my first workshop went, it was a great experience for +me and it seemed that the attendees all learnt something and found it +interesting. + +A couple of people mentioned about providing handouts to refer the code examples +whilst working on the exercises, rather than relying on the slides and avoiding +the need to sometimes switch back and forth between slides. I’ve found that I +can export the slide deck as PNGs or JPGs from Deckset, so I’ll definitely do +that next time. + +I’m giving the [Test-Driven Drupal][9] talk at the [Drupal Dev Days +conference][12] next week, and I’m hoping to give it again at other meetups and +events in the UK. If you’d like me to do either at your meetup or event, [get in +touch][13]. + +[0]: https://github.com/opdavies/drupal-testing-workshop +[1]: https://github.com/drupal-composer/drupal-project +[2]: https://docksal.io + +[3]: {{site.companies['microserve'].url}} [4]: +https://github.com/drupal-composer/drupal-project [5]: +https://www.drupal.org/project/examples [6]: +/articles/creating-a-custom-phpunit-command-for-docksal [7]: +/articles/using-environment-variables-settings-docksal [8]: +https://github.com/opdavies/drupal-testing-workshop-exercises [9]: +/talks/tdd-test-driven-drupal [10]: +https://www.drupal.org/project/private_message_queue [11]: +https://www.drupal.org/project/system_user [12]: +{{site.events.drupal_dev_days_18.url}} [13]: /contact [14]: +{{site.events.drupal_bristol.url}} [15]: /test-driven-drupal [16]: +https://groups.drupal.org/node/520891 diff --git a/source/_posts/drupal-vm-generator-updates.md b/source/_posts/drupal-vm-generator-updates.md new file mode 100644 index 00000000..761d86e0 --- /dev/null +++ b/source/_posts/drupal-vm-generator-updates.md @@ -0,0 +1,35 @@ +--- +title: Drupal VM Generator 2.9.1 Released +date: 2016-12-30 +excerpt: I’ve released some new versions of the Drupal VM Generator. +tags: + - drupal-vm-generator + - releases +--- + +The main updates are: + +- Fixed an `InvalidResponseException` that was thrown from within the + `boolean_as_string` Twig filter from the opdavies/twig-extensions library when + the `config:generate` command was run in non-interactive mode. +- Adding a working test suite for the existing commands, using PhpUnit and + Symfony’s Process component. This is now linked to [Travis CI][2], and the + tests are run on each commit and pull request. +- The version requirements have been changed to allow 2.7 versions of the used + Symfony Components, as well as the 3.x versions. This was done to resolve a + conflict when also installing Drush globally with Composer. + +## Next Steps + +Currently the project is based on Drupal VM 3.0.0 which is an outdated version +([4.1.0][3] was released today). Adding updates and supporting the newer +versions is a high priority, as well as keeping in sync with new releases. This +will be easier with the test suite in place. + +My initial thoughts are that version 2.10.0 will support Drupal VM 4.0.0, and if +needed, 2.11.0 will ship shortly afterwards and support Drupal VM 4.1.0. + +[0]: http://www.drupalvmgenerator.com +[1]: https://github.com/opdavies/drupal-vm-generator/tree/master/tests/Command +[2]: https://travis-ci.org/opdavies/drupal-vm-generator +[3]: https://github.com/geerlingguy/drupal-vm/releases/tag/4.1.0 diff --git a/source/_posts/drupalcamp-bristol-2018.md b/source/_posts/drupalcamp-bristol-2018.md new file mode 100644 index 00000000..a7f75443 --- /dev/null +++ b/source/_posts/drupalcamp-bristol-2018.md @@ -0,0 +1,46 @@ +--- +title: DrupalCamp Bristol 2018 Statement +date: 2018-01-30 +excerpt: Unfortunately, we won’t be running DrupalCamp Bristol this year. +tags: + - drupal-planet + - drupalcamp-bristol +meta: + image: + url: /images/blog/drupalcamp-bristol-17-logo.jpg + width: 228 + height: 448 + type: image/img +--- + +It’s with heavy hearts that we are announcing there won’t be a DrupalCamp +Bristol 2018. The committee have looked at the amount of work required to put +the camp on and the capacity we all have and the two numbers are irreconcilable. + +Seeing Drupalists from all over the country and from overseas come to Bristol to +share knowledge and ideas is something we take pride in. The past three camps +have been fantastic, but as a trend we have left it later and later to organise. + +This year is the latest we have left to organise and we believe this is because +we are all a bit fatigued right now, so it seems like a good place to stop and +take stock. + +In our washup of last year’s camp we spoke a lot about what DrupalCamp is and +who it is for. Traditionally we have tried to get a good mix of speakers from +within the Drupal community and from the wider tech community. This does mean we +dilute the ‘Drupal’ aspect of the camp, but the benefits it brings in terms of +bringing together different views gives the camp greater value in our eyes. + +It’s because of this mix of talks and wider shifts in the community in ‘getting +us off the island’ that we have been thinking about rebranding to reflect the +mix of talks that the camp hosts. The fact is DrupalCamps don’t just cover +Drupal anymore. There is Symfony, Composer, OOP principles, React, etc. + +We’ll take the gap this year to reevaluate who DrupalCamp Bristol is for and +where it fits into the schedule of excellent tech events that take place in +Bristol through the year, and we look forward to seeing you in 2019, refreshed +and more enthusiastic than ever! + +The DrupalCamp Bristol organising committee + +Tom, Ollie, Emily, Sophie, Rob, Mark diff --git a/source/_posts/drupalcamp-bristol-2019-speakers-sessions-announced.md b/source/_posts/drupalcamp-bristol-2019-speakers-sessions-announced.md new file mode 100644 index 00000000..bc6253dc --- /dev/null +++ b/source/_posts/drupalcamp-bristol-2019-speakers-sessions-announced.md @@ -0,0 +1,27 @@ +--- +title: Speakers and sessions announced for DrupalCamp Bristol 2019 +date: 2019-05-31 +excerpt: DrupalCamp Bristol is returning next month, and the accepted speakers and sessions have just been announced. +tags: + - dcbristol + - drupalcamp + - drupalcamp-bristol +--- + +

DrupalCamp Bristol is returning next month for a one-day, single-track conference, and we have just finished announcing the accepted sessions and speakers. It includes a mixture of new and returning speakers, presenting sessions including **Drupal in a microservice architecture**, **Automate to manage repetitive tasks with Ansible** and **Doing good with Drupal**.

+ +Find out more about all of our sessions and speakers on [the DrupalCamp Bristol +website][website], as well as view the schedule for the day. + +Also, at the time of writing, [early bird tickets are still available][tickets] +for a few more days! + +In the meantime, the videos from the 2017 Camp are on [our YouTube +channel][youtube], including the opening keynote from [Emma Karayiannis][emma]: + +{% include 'youtube-video' with { id: honnav4YlAA } %} + +[emma]: https://twitter.com/embobmaria +[tickets]: https://2019.drupalcampbristol.co.uk/tickets +[website]: https://2019.drupalcampbristol.co.uk +[youtube]: https://opdavi.es/dcbristol17-videos diff --git a/source/_posts/drupalcamp-bristol-early-bird-tickets-sessions-sponsors.md b/source/_posts/drupalcamp-bristol-early-bird-tickets-sessions-sponsors.md new file mode 100644 index 00000000..a3710daf --- /dev/null +++ b/source/_posts/drupalcamp-bristol-early-bird-tickets-sessions-sponsors.md @@ -0,0 +1,68 @@ +--- +title: DrupalCamp Bristol 2017 - Early Bird Tickets, Call for Sessions, Sponsors +date: 2017-05-15 +excerpt: In less than two months time, DrupalCamp Bristol will be back for our third year. +tags: + - drupal + - drupal-planet + - drupalcamp + - drupalcamp-bristol +meta: + image: + url: /assets/image/blog/drupalcamp-bristol-17-logo.jpg + height: 228 + width: 448 + type: image/jpg +--- + +

![DrupalCamp Bristol 2017 logo](/images/blog/drupalcamp-bristol-17-logo.jpg)

+ +In less than two months time, [DrupalCamp Bristol][0] will be back for our third +year! (July seems to come around quicker each year). This is this year’s +schedule and venues: + +- 30th June - CXO (Business) day - [Watershed][1] +- 1st July - Developer conference - [University of Bristol, School of + Chemistry][2] +- 2nd July - Contribution sprints - Venue TBC + +Today we announced [Emma Karayiannis][3] as our Saturday keynote speaker, and +we’ll be announcing some of the other speakers later this week. + +Not submitted your session yet? The [session submissions][12] are open until May +31st. We’re looking for talks not only on Drupal, but other related topics such +as PHP, Symfony, server administration/DevOps, project management, case studies, +being human etc. If you want to submit but want to ask something beforehand, +please [send us an email][4] or ping us on [Twitter][5]. + +Not spoken at a DrupalCamp before? No problem. We’re looking for both new and +experienced speakers, and have both long (45 minutes) and short (20 minutes) +talk slots available. + +Not bought your tickets yet? [Early bird tickets][10] for the CXO and conference +days are still available! The sprint day tickets are free but limited, so do +register for a ticket to claim your place. + +We still have [sponsorships opportunities][6] available (big thanks to +[Microserve][7], [Deeson][8] and [Proctors][9]) who have already signed up), but +be quick if you want to be included in our brochure so that we can get you added +before our print deadline! Without our sponsors, putting on this event each year +would not be possible. + +Any other questions? Take a look at [our website][0] or get in touch via +[Twitter][5] or [email][11]. + +[0]: https://2017.drupalcampbristol.co.uk +[1]: http://www.watershed.co.uk +[2]: http://www.bris.ac.uk/chemistry +[3]: http://emmakarayiannis.com +[4]: mailto:speakers@drupalcampbristol.co.uk +[5]: https://twitter.com/DrupalCampBris +[6]: https://2017.drupalcampbristol.co.uk/sponsorship +[7]: https://microserve.io +[8]: https://www.deeson.co.uk +[9]: http://www.proctors.co.uk +[10]: + https://www.eventbrite.co.uk/e/drupalcamp-bristol-2017-tickets-33574193316#ticket +[11]: mailto:info@drupalcampbristol.co.uk +[12]: https://2017.drupalcampbristol.co.uk/#block-dcb2017-page-title diff --git a/source/_posts/drupalcamp-london-2014.md b/source/_posts/drupalcamp-london-2014.md new file mode 100644 index 00000000..a40cd49e --- /dev/null +++ b/source/_posts/drupalcamp-london-2014.md @@ -0,0 +1,24 @@ +--- +title: DrupalCamp London 2014 +date: 2014-02-09 +excerpt: It's all booked, I'm going to be attending DrupalCamp London. +tags: + - drupal + - drupalcamp-london + - git + - git-flow +--- + +It's all booked, I'm going to be attending +[DrupalCamp London](http://2014.drupalcamplondon.co.uk) this year, my first +DrupalCamp! + +I'm going as a volunteer, so I'm going to be helping with the registrations on +the Saturday morning and for another couple hours elsewhere over the weekend. +I've also offered to help organise and oversee some code sprints, although I'm +definitely wanting to do some sprinting of my own and attend a few sessions. + +I'm looking forward to meeting some new people as well as catching up with some +people that I met at [DrupalCon Prague](http://prague2013.drupal.org). + +If you're also coming, see you there! diff --git a/source/_posts/drupalcamp-london-2019-tickets.md b/source/_posts/drupalcamp-london-2019-tickets.md new file mode 100644 index 00000000..dcd538ab --- /dev/null +++ b/source/_posts/drupalcamp-london-2019-tickets.md @@ -0,0 +1,39 @@ +--- +title: DrupalCamp London 2019 - Tickets Available and Call for Sessions +date: 2018-11-20 +excerpt: DrupalCamp London early-bird tickets are now available, and their call for sessions is open. +tags: + - conferences + - drupal + - drupalcamp + - drupalcamp-london +has_tweets: true +--- + +It was announced this week that [early-bird tickets are now available][0] for +[DrupalCamp London 2019][1], as well as their [call for sessions being open][2]. + +{% include 'tweet' with { + content: '

The time is finally here. You can now purchase your tickets. Early Bird finishes on 2nd January 2019 - https://t.co/aG6jstmWzv #Drupal

— DrupalCamp London (@DrupalCampLDN) November 19, 2018 +', +} %} + +I’ve attended, given talks and volunteered previously, would definitely +recommend others doing so, and I plan on attending and submitting again myself +for 2019. If there’s something in particular that you’d like to see me give a +talk on, let me know - I’d be happy to hear any suggestions. Alternatively, if +you’d like to submit and would like some help writing an abstract or want some +feedback on a talk idea, please get in touch. + +_Note: I am not an organiser of DrupalCamp London, nor am I involved with the +session selection process._ + +Hopefully there will be no [#uksnow][3] this year! + +DrupalCamp London is the 1-3 March 2019. Early bird tickets are available until +2 January 2019, and the call for sessions is open until 21 January. + +[0]: https://twitter.com/DrupalCampLDN/status/1064584179113971712 +[1]: https://drupalcamp.london +[2]: https://drupalcamp.london/get-involved/submit-a-session +[3]: /articles/tweets-drupalcamp-london diff --git a/source/_posts/drupalcamp-london-testing-workshop.mdx b/source/_posts/drupalcamp-london-testing-workshop.mdx new file mode 100644 index 00000000..d43ea9ef --- /dev/null +++ b/source/_posts/drupalcamp-london-testing-workshop.mdx @@ -0,0 +1,29 @@ +--- +title: Testing Workshop at DrupalCamp London 2020 +excerpt: This year, I’m teaching a workshop at DrupalCamp London. +tags: + - drupal + - drupalcamp + - testing +date: 2020-02-05 +lead_image: + url: /images/blog/testing-workshop-drupalcamp-london/lead.jpg +--- + + + +This year, I’m teaching a workshop at DrupalCamp London. + +The subject will be automated testing and test driven development in Drupal 8, +and it will be on Friday 13th March 2020, between 1pm and 5pm. + +In the workshop, I’ll cover the methodology, approaches and terminology involved +with automated testing, look at some examples and work through some exercises, +and then take a test driven development approach to creating a new Drupal +module. + +There are also other workshops on topics including Composer, Drupal Commerce, +profiling, and chatbots. + +For more information and to register, go to the +[DrupalCamp London website](https://opdavi.es/dclondon20 'Find out more and register on the DrupalCamp London website'). diff --git a/source/_posts/easier-git-repository-cloning-insteadof.md b/source/_posts/easier-git-repository-cloning-insteadof.md new file mode 100644 index 00000000..8ffbb0ed --- /dev/null +++ b/source/_posts/easier-git-repository-cloning-insteadof.md @@ -0,0 +1,82 @@ +--- +title: Easier Git Repository Cloning with insteadOf +date: 2019-03-07 +excerpt: How to simplify 'git clone' commands by using the insteadOf configuration option within your .gitconfig file. +tags: + - git +--- + +When working on client or open source projects, I clone a lot of +[Git](https://git-scm.com) repositories - either from GitHub, GitLab, Bitbucket +or Drupal.org. The standard `git clone` commands though provided by these sites +can be quite verbose with long repository URLs and use a mixture of different +protocols, and I’d regularly need to go back to each website and look up the +necessary command every time. + +For example, here is the command provided to clone Drupal’s +[Override Node Options module](https://www.drupal.org/project/override_node_options): + +``` +git clone --branch 8.x-2.x https://git.drupal.org/project/override_node_options.git +``` + +We can though simplify the command to make it easier and quicker to type, using +a Git configuration option called `insteadOf`. + +## What is insteadOf? + +From the +[Git documentation](https://git-scm.com/docs/git-config#git-config-urlltbasegtinsteadOf): + +> **url.[base].insteadOf:** +> +> Any URL that starts with this value will be rewritten to start, instead, with +> [base]. In cases where some site serves a large number of repositories, and +> serves them with multiple access methods, and some users need to use different +> access methods, this feature allows people to specify any of the equivalent +> URLs and have Git automatically rewrite the URL to the best alternative for +> the particular user, even for a never-before-seen repository on the site. When +> more than one insteadOf strings match a given URL, the longest match is used. + +Whilst examples are sparse, +[it seems like](https://stackoverflow.com/questions/1722807/how-to-convert-git-urls-to-http-urls) +insteadOf is used for resolving protocol issues with repository URLs. However, +we can use it to simplify our clone commands, as mentioned above. + +## Example: cloning Drupal contrib projects + +When working on Drupal core, or on a module, theme or distribution, you need to +have a cloned version of that repository to generate patch files from, and apply +patches to. + +Again, here is the provided command to clone the Override Node Options module: + +``` +git clone --branch 8.x-2.x https://git.drupal.org/project/override_node_options.git +``` + +At the time of writing, the Git repository URL follow this same format - +`https://git.drupal.org/project/{name}.git` (also the `.git` file extension is +optional). + +To shorten and simplify this, I can add this snippet to my `~/.gitconfig` file: + +``` +[url "https://git.drupal.org/project/"] + insteadOf = do: + insteadOf = drupal: +``` + +With that added, I can now instead run `git clone drupal:{name}` or +`git clone do:{name}` to clone the repository, specifying the project’s machine +name. + +For example, to clone the Override Node Options module, I can now do this using +just `git clone drupal:override_node_options`. + +This, I think, is definitely quicker and easier! + +## Resources + +You can view my entire `.gitconfig` file, as well as my other dotfiles, in +[my dotfiles repository on GitHub](https://github.com/opdavies/dotfiles/blob/master/.gitconfig). diff --git a/source/_posts/easier-sculpin-commands-composer-npm-scripts.md b/source/_posts/easier-sculpin-commands-composer-npm-scripts.md new file mode 100644 index 00000000..9b844e7b --- /dev/null +++ b/source/_posts/easier-sculpin-commands-composer-npm-scripts.md @@ -0,0 +1,78 @@ +--- +title: Easier Sculpin Commands with Composer and NPM Scripts +date: 2017-01-07 +excerpt: In this video, I show you how I've simplied my Sculpin and Gulp workflow using custom Composer and NPM scripts. +tags: + - composer + - gulp + - sculpin +--- + +In this video, I show you how I've simplied my Sculpin and Gulp workflow using +custom Composer and NPM scripts. + +My website includes several various command line tools - e.g. [Sculpin][4], +[Gulp][5] and [Behat][6] - each needing different arguments and options, +depending on the command being run. For example, for Sculpin, I normally include +several additional options when viewing the site locally - the full command that +I use is +`./vendor/bin/sculpin generate --watch --server --clean --no-interaction`. +Typing this repeatedly is time consuming and could be easily mis-typed, +forgotten or confused with other commands. + +In this video, I show you how I've simplied my Sculpin and Gulp workflow using +custom Composer and NPM scripts. + +
+ +
+ +## Scripts + +Here are the scripts that I’m using - they are slightly different from those in +the video. I use the `--generate` and `--watch` options for Sculpin and the +`gulp watch` command for NPM. I had to change these before the recording as I +was using the [demo magic][0] script to run the commands, and existing from a +watch session was also ending the script process. + +### composer.json + +```json +"scripts": { + "clean": "rm -rf output_*/", + "dev": "sculpin generate --clean --no-interaction --server --watch", + "production": "sculpin generate --clean --no-interaction --env='prod' --quiet" +} +``` + +Run with `composer run `, e.g. `composer run dev`. + +### package.json + +```json +"scripts": { + "init": "yarn && bower install", + "dev": "gulp watch", + "production": "gulp --production" +} +``` + +Run with `npm run `, e.g. `npm run production`. + +You can also take a look at the full [composer.json][1] and [package.json][2] +files within my site repository on [GitHub][3]. + +## Resources + +- [Composer scripts][7] +- [oliverdavies.uk composer.json][1] +- [oliverdavies.uk package.json][2] + +[0]: https://github.com/paxtonhare/demo-magic +[1]: https://github.com/opdavies/oliverdavies.uk/blob/master/composer.json +[2]: https://github.com/opdavies/oliverdavies.uk/blob/master/package.json +[3]: https://github.com/opdavies/oliverdavies.uk +[4]: https://sculpin.io +[5]: http://gulpjs.com +[6]: http://behat.org +[7]: https://getcomposer.org/doc/04-schema.md#scripts diff --git a/source/_posts/easily-embed-typekit-fonts-your-drupal-website.md b/source/_posts/easily-embed-typekit-fonts-your-drupal-website.md new file mode 100644 index 00000000..4defa315 --- /dev/null +++ b/source/_posts/easily-embed-typekit-fonts-your-drupal-website.md @@ -0,0 +1,32 @@ +--- +title: Easily Embed TypeKit Fonts into your Drupal Website +date: 2011-02-14 +excerpt: How to use the @font-your-face module to embed TypeKit fonts into your Drupal website. +tags: + - drupal-6 + - drupal-planet + - typekit +--- + +To begin with, you will need to +[register for a TypeKit account](https://typekit.com/plans) - there is a free +version if you just want to try it out. + +Next, you'll need to create a kit that contains the fonts that you want to use +on your website. I've used +[FF Tisa Web Pro](http://typekit.com/fonts/ff-tisa-web-pro). + +Under 'Kit Settings', ensure that your website domain (e.g. mysite.com) is +listed under 'Domains'. + +Download and install the +[@font-your-face](http://drupal.org/project/fontyourface) module onto your +Drupal site, and to go admin/settings/fontyourface to configure it. Enter +[your TypeKit API key](https://typekit.com/account/tokens), and click 'Import +Typekit' to import your kits and fonts. + +Go to admin/dist/themes/fontyourface, and click 'Browse fonts to enable'. Click +on the name of the font that you want to enable, check 'Enabled', and click +'Edit font' to save your changes. + +With the font enabled, you can now use it in your CSS. diff --git a/source/_posts/entityform.md b/source/_posts/entityform.md new file mode 100644 index 00000000..e6029884 --- /dev/null +++ b/source/_posts/entityform.md @@ -0,0 +1,62 @@ +--- +title: Programmatically Load an Entityform in Drupal 7 +date: 2015-12-22 +excerpt: How to programmatically load, render and embed an entityform in Drupal 7. +tags: + - drupal + - drupal-7 + - drupal-planet + - entityform +--- + +I recently had my first experience using the +[Entityform module](https://www.drupal.org/project/entityform) in a project. It +was quite easy to configure with different form types, but then I needed to +embed the form into an overlay. I was expecting to use the `drupal_get_form()` +function and render it, but this didn’t work. + +Here are the steps that I took to be able to load, render and embed the form. + +## Loading the Form + +The first thing that I needed to do to render the form was to load an empty +instance of the entityform using `entityform_empty_load()`. In this example, +`newsletter` is the name of my form type. + +```php +$form = entityform_empty_load('newsletter'); +``` + +This returns an instance of a relevant `Entityform` object. + +## Rendering the Form + +The next step was to be able to render the form. I did this using the +`entity_form_wrapper()` function. + +As this function is within the `entityform.admin.inc` file and not autoloaded by +Drupal, I needed to include it using `module_load_include()` so that the +function was available. + +```php +module_load_include('inc', 'entityform', 'entityform.admin'); + +$output = entityform_form_wrapper($form, 'submit', 'embedded'), +``` + +The first argument is the `Entityform` object that was created in the previous +step (I’ve [submitted a patch](https://www.drupal.org/node/2639584) to type hint +this within entityform so that it’s clearer what is expected), which is +required. + +The other two arguments are optional. The second argument is the mode (`submit` +is the default value), and the last is the form context. `page` is the default +value, for use on the submit page, however I changed this to `embedded`. + +I could then pass this result into my theme function to render it successfully +within the relevant template file. + +## Resources + +- [The entityform module](https://www.drupal.org/project/entityform) +- [My issue and patch to add the type hint to the entityform_form_wrapper function](https://www.drupal.org/node/2639584) diff --git a/source/_posts/experimenting-events-drupal-8.md b/source/_posts/experimenting-events-drupal-8.md new file mode 100644 index 00000000..790c7614 --- /dev/null +++ b/source/_posts/experimenting-events-drupal-8.md @@ -0,0 +1,81 @@ +--- +title: Experimenting with events in Drupal 8 +date: 2018-08-21 +excerpt: Trying a different way of structuring Drupal modules, using event subscribers and autowiring. +tags: + - drupal + - drupal-8 + - drupal-planet + - php + - symfony +promoted: true +--- + +I’ve been experimenting with moving some code to Drupal 8, and I’m quite +intrigued by a different way that I’ve tried to structure it - using event +subscribers, building on some of the takeaways from Drupal Dev Days. + +Here is how this module is currently structured: + +![](/images/blog/events-drupal-8/1.png){.border .p-1} + +Note that there is no `opdavies_blog.module` file, and rather than calling +actions from within a hook like `opdavies_blog_entity_update()`, each action +becomes it’s own event subscriber class. + +This means that there are no long `hook_entity_update` functions, and instead +there are descriptive, readable event subscriber class names, simpler action +code that is responsibile only for performing one task, and you’re able to +inject and autowire dependencies into the event subscriber classes as services - +making it easier and cleaner to use dependency injection, and simpler write +tests to mock dependencies when needed. + +The additional events are provided by the +[Hook Event Dispatcher module](https://www.drupal.org/project/hook_event_dispatcher). + +## Code + +`opdavies_blog.services.yml`: + +```yaml +services: + Drupal\opdavies_blog\EventSubscriber\PostToMedium: + autowire: true + tags: + - { name: event_subscriber } + + Drupal\opdavies_blog\EventSubscriber\SendTweet: + autowire: true + tags: + - { name: event_subscriber } +``` + +
+Adding `autowire: true` is not required for the event subscriber to work. I’m using it to automatically inject any dependencies into the class rather than specifying them separately as arguments. +
+ +`src/EventSubscriber/SendTweet.php`: + +```php +namespace Drupal\opdavies_blog\EventSubscriber; + +use Drupal\hook_event_dispatcher\Event\Entity\EntityUpdateEvent; +use Drupal\hook_event_dispatcher\HookEventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +class SendTweet implements EventSubscriberInterface { + + ... + + public static function getSubscribedEvents() { + return [ + HookEventDispatcherInterface::ENTITY_UPDATE => 'sendTweet', + ]; + } + + public function sendTweet(EntityUpdateEvent $event) { + // Perform checks and send the tweet. + } + +} +``` diff --git a/source/_posts/feature-flags-sculpin.md b/source/_posts/feature-flags-sculpin.md new file mode 100644 index 00000000..5b80b0d6 --- /dev/null +++ b/source/_posts/feature-flags-sculpin.md @@ -0,0 +1,103 @@ +--- +title: "Using Feature Flags with Sculpin" +excerpt: | + How I've started using feature flags within a client's Sculpin website. +tags: [sculpin] +date: 2022-01-09 +--- + +
+ +
+ +## Background + +I was asked last week to add a new feature, a Facebook pixel for measuring and +building advertising campaigns, to a client's website which I built using the +[Sculpin](https://sculpin.io) static site generator. + +The site uses settings within the `app/config/sculpin_site.yml` file for +storing site IDs and usernames. For this, I would add something like: + +```yaml +facebook: + pixel: + id: "abc123" +``` + +It can then be retrieved with `{{ site.facebook.pixel.id }}`. + +If I then needed to disable the pixel, then I'd typically remove the pixel +ID: + +```yaml +facebook: + pixel: + id: ~ +``` + +## Introducing feature flags + +A technique that I like to use on other projects is using +[feature flags](https://www.atlassian.com/continuous-delivery/principles/feature-flags) +(aka feature toggles). + +Whilst, in this instance, a feature flag wouldn't separate deploying code from +toggling a feature - a static site will need to be re-generated and deployed - +I thought that there was value in being able to easily toggle a feature without +changing its configuration or removing code within the site's templates. + +## Feature flags in Sculpin + +My Sculpin feature flag implementation was to add a `feature_flags` key within +`sculpin_site.yml`, with each feature's name as the key and a boolean value to +set whether it's enabled - similar to how the Drupal 7 version of the +[Feature Toggle module](https://www.drupal.org/project/feature_toggle) works. + +This is how I added the Facebook pixel feature flag: + +```yaml +feature_flags: + add_facebook_pixel: true +``` + +## Using the Facebook pixel feature flag + +The Facebook pixel code is stored within it's own partial that I can include +from my `source/_layouts/app.html.twig` layout, including the pixel ID and +whether or not the feature flag is enabled. + +```twig +{% verbatim %} +{% include "facebook-pixel" with { + + + is_enabled: site.feature_flags.add_facebook_pixel, + pixel_id: site.facebook.pixel.id, +} only %} +{% endverbatim %} +``` + +Within the partial, I can check that both the feature flag is enabled and that +there is a Facebook pixel ID, and only add the pixel code if both conditions +return a truthy value. + +```twig +{% if is_enabled and pixel_id %} + +{% endif %} +``` + +Now the pixel can be removed just by setting `add_facebook_pixel: false` in +`sculpin_site.yml`, and without changing any other configuration or templates. diff --git a/source/_posts/finding-the-last-commit-that-a-patch-applies-to.md b/source/_posts/finding-the-last-commit-that-a-patch-applies-to.md new file mode 100644 index 00000000..bf9bbca7 --- /dev/null +++ b/source/_posts/finding-the-last-commit-that-a-patch-applies-to.md @@ -0,0 +1,49 @@ +--- +title: Finding the last commit that a patch applies to +excerpt: How to find the last commit in a Git repository that a patch applies to. +date: 2020-03-26 +tags: + - bash + - git +draft: true +--- + +```bash +#!/usr/bin/env bash + +# https://www.drupal.org/files/issues/2018-08-28/group-configurable-entities-as-group-content-2797793-58.patch + +patch_filename=group-configurable-entities-as-group-content-2797793-58.patch +first_commit=6e8c22a +last_commit=8.x-1.x + +find_commits_between() { + first_commit=$1 + last_commit=$2 + + git rev-list --reverse --ancestry-path $first_commit^...$last_commit +} + +reset_repo() { + git reset --hard $1 >& /dev/null +} + +apply_patch() { + git apply --check $patch_filename >& /dev/null +} + +for sha1 in $(find_commits_between $first_commit $last_commit); do + echo "Trying ${sha1}..." + + reset_repo $sha1 + apply_patch + + if [[ $? -eq 0 ]]; then + echo "Patch applies" + continue + fi + + echo "Patch does not apply" + exit 1 +done +``` diff --git a/source/_posts/fixing-drupal-simpletest-issues-inside-docker-containers.md b/source/_posts/fixing-drupal-simpletest-issues-inside-docker-containers.md new file mode 100644 index 00000000..ad7e045b --- /dev/null +++ b/source/_posts/fixing-drupal-simpletest-issues-inside-docker-containers.md @@ -0,0 +1,130 @@ +--- +title: Fixing Drupal SimpleTest issues inside Docker Containers +date: 2017-05-05 +excerpt: How I managed to get my Drupal SimpleTest tests to run and pass within Docker containers. +tags: + - docker + - drupal + - drupal-planet + - simpletest + - testing +--- + +I’ve been a Drupal VM user for a long time, but lately I’ve been using a +combination Drupal VM and Docker for my local development environment. There +were a couple of issues preventing me from completely switching to Docker - one +of which being that when I tried running of my Simpletest tests, a lot of them +would fail where they would pass when run within Drupal VM. + +Here’s an excerpt from my `docker-compose.yml` file: + +**TL;DR** You need to include the name of your web server container as the +`--url` option to `run-scripts.php`. + +I’ve been a [Drupal VM][1] user for a long time, but lately I’ve been using a +combination Drupal VM and [Docker][0] for my local development environment. +There were a couple of issues preventing me from completely switching to +Docker - one of which being that when I tried running of my Simpletest tests, a +lot of them would fail where they would pass when run within Drupal VM. + +Here’s an excerpt from my `docker-compose.yml` file: + +```yaml +services: + php: + image: wodby/drupal-php:5.6 + volumes: + - ./repo:/var/www/html + + nginx: + image: wodby/drupal-nginx:7-1.10 + environment: + NGINX_BACKEND_HOST: php + NGINX_SERVER_ROOT: /var/www/html/web + ports: + - "80:80" + volumes_from: + - php +... +``` + +Nginx and PHP-FPM are running in separate containers, the volumes are shared +across both and the Nginx backend is set to use the `php` container. + +This is the command that I was using to run the tests: + +```bash +$ docker-compose run --rm \ + -w /var/www/html/web \ + php \ + php scripts/run-tests.sh \ + --php /usr/local/bin/php \ + --class OverrideNodeOptionsTestCase +``` + +This creates a new instance of the `php` container, sets the working directory +to my Drupal root and runs Drupal’s `run-tests.sh` script with some arguments. +In this case, I'm running the `OverrideNodeOptionsTestCase` class for the +override_node_options tests. Once complete, the container is deleted because of +the `--rm` option. + +This resulted in 60 of the 112 tests failing, whereas they all passed when run +within a Drupal VM instance. + +``` +Test summary +------------ + +Override node options 62 passes, 60 fails, 29 exceptions, and 17 debug messages + +Test run duration: 2 min 25 sec +``` + +Running the tests again with the`--verbose` option, I saw this message appear in +the output below some of the failing tests: + +> simplexml_import_dom(): Invalid Nodetype to import + +\*\*Up After checking that I had all of the required PHP extensions installed, I +ran `docker-compose exec php bash` to connect to the `php` container and ran +`curl http://localhost` to check the output. Rather than seeing the HTML for the +site, I got this error message: + +> curl: (7) Failed to connect to localhost port 80: Connection refused + +Whereas `curl http://nginx` returns the HTML for the page, so included it with +the `--url` option to `run-tests.sh`, and this resulted in my tests all passing. + +```bash +$ docker-compose run --rm \ + -w /var/www/html/web \ + php \ + php scripts/run-tests.sh \ + --php /usr/local/bin/php \ + --url http://nginx \ + --class OverrideNodeOptionsTestCase +``` + +``` +Test summary +------------ + +Override node options 121 passes, 0 fails, 0 exceptions, and 34 debug messages + +Test run duration: 2 min 31 sec +``` + +**Note:** In this example I have separate `nginx` and `php` containers, but I've +tried and had the same issue when running Nginx and PHP-FPM in the same +container - e.g. called `app` - and still needed to add `--url http://app` in +order for the tests to run successfully. + +I don’t know if this issue is macOS specfic (I know that [Drupal CI][2] is based +on Docker, and I don’t know if it’s an issue) but I’m going to test also on my +Ubuntu Desktop environment and investigate further and also compare the test run +times for Docker in macOS, Docker in Ubuntu and within Drupal VM. I’m also going +to test this with PHPUnit tests with Drupal 8. + +[0]: https://www.docker.com +[1]: https://www.drupalvm.com +[2]: https://www.drupal.org/drupalorg/docs/drupal-ci diff --git a/source/_posts/forward-one-domain-another-using-modrewrite-htaccess.md b/source/_posts/forward-one-domain-another-using-modrewrite-htaccess.md new file mode 100644 index 00000000..54a9bf07 --- /dev/null +++ b/source/_posts/forward-one-domain-another-using-modrewrite-htaccess.md @@ -0,0 +1,29 @@ +--- +title: Forward one domain to another using mod_rewrite and .htaccess +date: 2012-05-23 +excerpt: How to use the .htaccess file to forward to a different domain. +tags: + - .htaccess + - apache + - code + - drupal + - mod_rewrite +--- + +How to use the .htaccess file to forward to a different domain. + +Within the mod_rewrite section of your .htaccess file, add the following lines: + + RewriteCond %{HTTP_HOST} ^yoursite\.co\.uk$ + RewriteRule (.*) http://yoursite.com/$1 [R=301,L] + +This automatically forwards any users from http://yoursite.co.uk to +http://yoursite.com. This can also be used to forward multiple domains: + + RewriteCond %{HTTP_HOST} ^yoursite\.co\.uk$ [OR] + RewriteCond %{HTTP_HOST} ^yoursite\.info$ [OR] + RewriteCond %{HTTP_HOST} ^yoursite\.biz$ [OR] + RewriteCond %{HTTP_HOST} ^yoursite\.eu$ + RewriteRule (.*) http://yoursite.com/$1 [R=301,L] + +If any of the RewriteCond conditions apply, then the RewriteRule is executed. diff --git a/source/_posts/git-format-patch-your-friend.md b/source/_posts/git-format-patch-your-friend.md new file mode 100644 index 00000000..4f929dd3 --- /dev/null +++ b/source/_posts/git-format-patch-your-friend.md @@ -0,0 +1,136 @@ +--- +title: git format-patch is your Friend +date: 2014-05-21 +excerpt: An explanation of the "git format-patch" command, and how it could be used in Drupal's Git workflow. +tags: + - drupal + - drupal-planet + - git + - patches +--- + +An explanation of the "git format-patch" command, and how it could be used in +Drupal's Git workflow. + +## The Problem + +As an active contributor to the [Drupal](http://drupal.org) project, I spend a +lot of time working with other peoples’ modules and themes, and occassionally +have to fix a bug or add some new functionality. + +In the Drupal community, we use a patch based workflow where any changes that I +make get exported to a file detailing the differences. The patch file (\*.patch) +is attached to an item in an issue queue on Drupal.org, applied by the +maintainer to their local copy of the code and reviewed, and hopefully +committed. + +There is an option that the maintainer can add to the end of their commit +message. + +For example: + +```bash +--author="opdavies " +``` + +This differs slightly different for each Drupal user, and the code can be found +on their Drupal.org profile page. + +If this is added to the end of the commit message, the resulting commit will +show that it was committed by the maintainer but authored by a different user. +This will then display on Drupal.org that you’ve made a commit to that project. + +![A screenshot of a commit that was authored by rli but committed by opdavies](/images/blog/git-format-patch.png) + +The problem is that some project maintainers either don’t know about this option +or occasionally forget to add it. [Dreditor](http://dreditor.org) can suggest a +commit message and assign an author, but it is optional and, of course, not all +maintainers use Dreditor (although they probably should). + +The `git format-patch` command seems to be the answer, and will be my preferred +method for generating patch files in the future rather than `git diff`. + +## What does it do Differently? + +From the [manual page](http://git-scm.com/docs/git-format-patch): + +> Prepare each commit with its patch in one file per commit, formatted to +> resemble UNIX mailbox format. The output of this command is convenient for +> e-mail submission or for use with git am. + +Here is a section of a patch that I created for the +[Metatag module](http://drupal.org/project/metatag) using `git format-patch`: + +```bash +From 80c8fa14de7f4a83c2e70367aab0aedcadf4f3b0 Mon Sep 17 00:00:00 2001 +From: Oliver Davies <oliver@oliverdavies.co.uk> +Subject: [PATCH] Exclude comment entities when checking if this is the page, + otherwise comment_fragment.module will break metatag +--- +``` + +As mentioned above, the patch is structured in an email format. The commit +message is used as the subject line, and the date that the commit was made +locally is used for the date. What we’re interested in is the “From” value. This +contains your name and email address from your `~/.gitconfig` file and is used +to author the patch automatically. + +Everything below this is the same as a standard patch file, the same as if was +generated with `git diff`. + +The full patch file can be found at +. + +## The Process + +How did I create this patch? Here are the steps that I took: + +1. Clone the source repository using + `$ git clone --branch 7.x-1.x http://git.drupal.org/project/metatag.git` and + move into that directory. +2. Create a branch for this patch using + `$ git checkout -b 2265447-comment-fragment-conflict`. +3. Add and commit any changes as normal. +4. Generate the patch file using + `$ git format-patch 7.x-1.x --stdout > metatag-comment-fragment-conflict-2265447-4.patch`. + +_Note:_ I am defining 7.x-1.x in the last step as the original branch to compare +(i.e. the original branch that we forked to make our issue branch). This will +change depending on the project that you are patching, and it’s version number. +Also, commits should always be made against the development branch and not the +stable release. + +By default, a separate patch file will be created for each commit that we’ve +made. This is overridden by the `--stdout` option which combines all of the +patches into a single file. This is the recommended approach when uploading to +Drupal.org. + +The resulting patch file can be uploaded onto a Drupal.org issue queue, reviewed +by the Testbot and applied by a module maintainer, and you automatically get the +commit attributed. Problem solved. + +## Committing the Patch + +If you need to commit a patch that was created using `git format-patch`, the +best command to do this with is the `git am` command. + +For example, within your repository, run: + +```bash +$ git am /path/to/file +$ git am ~/Code/metatag-comment-fragment-conflict-2265447-4.patch +``` + +You should end up with some output similar to the following: + +```bash +Applying: #2272799 Added supporters section +Applying: #2272799 Added navigation tabs +Applying: #2272799 Fixed indentation +Applying: #2272799 Replaced URL +``` + +Each line is the commit message associated with that patch. + +Assuming that there are no errors, you can go ahead and push your updated code +into your remote repository. diff --git a/source/_posts/github-actions-phpunit-colours.md b/source/_posts/github-actions-phpunit-colours.md new file mode 100644 index 00000000..5fad2fee --- /dev/null +++ b/source/_posts/github-actions-phpunit-colours.md @@ -0,0 +1,11 @@ +--- +title: Coloured output with PHPUnit and GitHub Actions +excerpt: How to have colours in your PHPUnit output when running with GitHub Actions. +date: 2020-08-12 +tags: + - github-actions + - phpunit + - testing +--- + + diff --git a/source/_posts/going-drupalcon.md b/source/_posts/going-drupalcon.md new file mode 100644 index 00000000..18ce7b23 --- /dev/null +++ b/source/_posts/going-drupalcon.md @@ -0,0 +1,16 @@ +--- +title: Going to DrupalCon +date: 2013-07-26 +excerpt: Precedent are sending myself and two of our other Drupal Developers to Drupalcon Prague. +tags: + - drupalcon + - precedent +--- + +[Precedent](http://www.precedent.co.uk) are sending myself and two of our other +Drupal Developers to [Drupalcon Prague](http://prague2013.drupal.org). + +Having wanted to attend the last few Drupalcons (London, especially) but not +being able to, I'm definitely looking forward to this one. + +See you there! diff --git a/source/_posts/going-full-vim.md b/source/_posts/going-full-vim.md new file mode 100644 index 00000000..453e7051 --- /dev/null +++ b/source/_posts/going-full-vim.md @@ -0,0 +1,50 @@ +--- +title: Going "Full Vim" for my development work +excerpt: I've recently been using Neovim for all of my coding, as well as for my blog posts and slide decks. +tags: + - vim +date: 2021-07-08 +--- + +For the past few months, I've gone "full Vim" ([Neovim][], to be exact) when writing any code - including anything for work or freelance projects, this blog post, and any presentation slide decks. + +I've been a long-time casual Vim user, enabling Vi or Vim mode within other editors, including Sublime Text, PhpStorm, and VS Code, and using Vim to write Git commit messages or to edit single files before closing it again. I remember searching how to add Vim features like relative line numbers in other editors, and trying things that would work within Vim but not when using in a plugin or extension. + +I've seen people and companies like [Lorna Jane Mitchell][], Suz Hinton ([noopkat][]), and [Thoughtbot][] using Vim in their presentations and videos for a long time but I haven't tried to switch before myself. + +Inspired by them and others including [Robin Malfait][], [TheAltF4Stream][], [Codico][], [Michael Dyrynda][], [ThePrimeagen][] with their recent live streams, videos, podcasts, and courses, I decided to give it a try. + +## Plugins + +You can see the [full list of plugins on GitHub](https://github.com/opdavies/dotfiles/blob/main/.config/nvim/plugins.vim), but here are some of the main ones that I've been using so far: + +- [fzf](https://github.com/junegunn/fzf.vim) - a fuzzy-finder to easily locate and open files. +- [CoC](https://github.com/neoclide/coc.nvim) and [Intelephense](https://intelephense.com) - adds auto-completion and code snippet support, including refactorings such as renaming symbols. +- [NERDTree](https://github.com/preservim/nerdtree) - a tree explorer, though I usually use the fuzzy finder so this isn't used that often. +- [Git gutter](https://github.com/airblade/vim-gitgutter) - displays Git diff information in the gutter of the current file. +- [Blamer](https://github.com/APZelos/blamer.nvim) - inspired by the GitLens plugin for VS Code, displays `git blame` information for the current line. +- [Nord](https://github.com/arcticicestudio/nord-vim), [jellybeans](https://github.com/nanotech/jellybeans.vim), and [ayu](https://github.com/ayu-theme/ayu-vim) - different themes that I'm trying and switching between. + +## Configuration + +If you'd like to see my full Neovim configuration, see the `.config/nvim` directory and the `init.vim` file in my [Dotfiles repository on GitHub](https://github.com/opdavies/dotfiles/tree/main/.config/nvim). + +## Conclusion + +I'm enjoying my first few months of using Vim full-time, and so far, I haven't looked back. I''ve had no issues using it in a Windows/WSL 2 environment either, which was great. + +I have a [cheat sheet on GitHub Gists](https://gist.github.com/opdavies/f944261b54f70b43f2297cab6779cf59) where I note the current things that I'm trying to learn and commit to memory. + +As I use it and learn more, I'm sure that I'll be posting more Vim-related content here too. + +Have any Vim/Neovim suggestions, tips, or tricks? Let me know on Twitter. + +[codico]: https://www.twitch.tv/codico +[lorna jane mitchell]: https://lornajane.net +[michael dyrynda]: https://dyrynda.com.au +[neovim]: https://neovim.io +[noopkat]: https://www.twitch.tv/noopkat +[robin malfait]: https://twitter.com/malfaitrobin +[thealtf4stream]: https://www.twitch.tv/thealtf4stream +[theprimeagen]: https://twitter.com/theprimeagen +[thoughtbot]: https://thoughtbot.com diff --git a/source/_posts/how-add-date-popup-calendar-custom-form.md b/source/_posts/how-add-date-popup-calendar-custom-form.md new file mode 100644 index 00000000..807b6b54 --- /dev/null +++ b/source/_posts/how-add-date-popup-calendar-custom-form.md @@ -0,0 +1,44 @@ +--- +title: How to add a date popup calendar onto a custom form +date: 2012-05-23 +excerpt: How to use a date popup calendar within your custom module. +tags: + - calendar + - date + - drupal + - drupal-7 + - drupal-planet + - form-api + - forms +--- + +How to use a date popup calendar within your custom module. + +First, I need to download the +[Date](http://drupal.org/project/date 'Date module on Drupal.org') module, and +make my module dependent on date_popup by adding the following line into my +module's .info file. + +```ini +dependencies[] = date_popup +``` + +Within my form builder function: + +```php +$form['date'] = array( + '#title' => t('Arrival date'), + + // Provided by the date_popup module + '#type' => 'date_popup', + + // Uses the PHP date() format - http://php.net/manual/en/function.date.php + '#date_format' => 'j F Y', + + // Limits the year range to the next two upcoming years + '#date_year_range' => '0:+2', + + // Default value must be in 'Y-m-d' format. + '#default_value' => date('Y-m-d', time()), +); +``` diff --git a/source/_posts/how-create-apply-patches.md b/source/_posts/how-create-apply-patches.md new file mode 100644 index 00000000..ab1e67a8 --- /dev/null +++ b/source/_posts/how-create-apply-patches.md @@ -0,0 +1,50 @@ +--- +title: How to Create and Apply Patches +date: 2010-10-10 +excerpt: How to create and apply patches, ready for the Drupal.org issue queues. +tags: + - drupal-6 + - drupal-planet + - modules + - patches +--- + +Earlier this year, I posted a solution to +[an issue](http://drupal.org/node/753898) on the Drupal.org issue queue. +Originally, I just posted the code back onto the issue, but have now created a +patch that can easily be applied to any Drupal 6 installation. Here is a +run-through of the process of creating and applying a patch. In this case, I +made changes to the `user_pass_validate()` function that's found within +`modules/user/user.pages.inc`. + +To begin with, a download a fresh copy of Drupal 6.19 and created a copy of the +original user.pages.inc file. Within the duplicate file, I made the same changes +to the function that I did in earlier code, and saved the changes. Now, within +my Terminal, I can navigate to Drupal's root directory and create the patch. + +```bash +diff -rup modules/user/user.pages.inc modules/user/user.pages2.inc > /Users/oliver/Desktop/different_messages_for_blocked_users.patch +``` + +This command compares the differences between the two files, and creates the +specified patch file. + +To apply the patch to my Drupal installation, I go back to Terminal and run the +following code: + +```bash +patch -p0 < /Users/oliver/Desktop/different_messages_for_blocked_users.patch +``` + +If, for some reason, I need to reverse the patch, I can run this code: + +```bash +patch -p0 -R < /Users/oliver/Desktop/different_messages_for_blocked_users.patch +``` + +And that's it! + +There is also a Git patch creation workflow, which is described at +. Thanks to +[Randy Fay](http://randyfay.com) for making me aware of this, and suggesting a +slight change to my original patch creation command. diff --git a/source/_posts/how-fix-vagrant-loading-wrong-virtual-machine.md b/source/_posts/how-fix-vagrant-loading-wrong-virtual-machine.md new file mode 100644 index 00000000..38a324dc --- /dev/null +++ b/source/_posts/how-fix-vagrant-loading-wrong-virtual-machine.md @@ -0,0 +1,26 @@ +--- +title: How to fix Vagrant Loading the Wrong Virtual Machine +date: 2014-10-06 +excerpt: Here are the steps that I took to fix Vagrant and point it back at the correct VM. +tags: + - vagrant + - virtualbox +--- + +A few times recently, I've had instances where +[Vagrant](https://www.vagrantup.com) seems to have forgotten which virtual +machine it's supposed to load, probably due to renaming a project directory or +the .vagrant directory being moved accidentally. + +Here are the steps that I took to fix this and point Vagrant back at the correct +VM. + +1. Stop the machine from running using the `$ vagrant halt` command. +1. Use the `$ VBoxManage list vms` command to view a list of the virtual + machines on your system. Note the ID of the correct VM that should be + loading. For example, + `"foo_default_1405481857614_74478" {e492bfc3-cac2-4cde-a396-e81e37e421e2}`. + The number within the curly brackets is the ID of the virtual machine. +1. Within the .vagrant directory in your project (it is hidden by default), + update the ID within the machines/default/virtualbox/id file. +1. Start the new VM with `$ vagrant up`. diff --git a/source/_posts/how-install-configure-subversion-svn-server-ubuntu.md b/source/_posts/how-install-configure-subversion-svn-server-ubuntu.md new file mode 100644 index 00000000..4cfac16e --- /dev/null +++ b/source/_posts/how-install-configure-subversion-svn-server-ubuntu.md @@ -0,0 +1,178 @@ +--- +title: How to Install and Configure Subversion (SVN) Server on Ubuntu +date: 2011-10-19 +excerpt: How to install and configure your own SVN server. +tags: + - svn + - ubuntu + - version-control +--- + +Recently, I needed to set up a Subversion (SVN) server on a Ubuntu Linux server. +This post is going to outline the steps taken, and the commands used, to install +and configure the service. + +Note: As I was using Ubuntu, I was using the 'apt-get' command to download and +install the software packages. If you're using a different distribution of +Linux, then this command may be different. I'm also assuming that Apache is +already installed. + +Firstly, I'm going to ensure that all of my installed packages are up to date, +and install any available updates. + +```bash +$ sudo apt-get update +``` + +Now, I need to download the subversion, subversion-tools and libapache2 +packages. + +```bash +$ sudo apt-get install subversion subversion-tools libapache2-svn +``` + +These are all of the packages that are needed to run a Subversion server. + +## Create subversion directory + +Now, I need to create the directory where my repositories are going to sit. I've +chosen this directory as I know that it's one that is accessible to my managed +backup service. + +```bash +$ sudo mkdir /home/svn +``` + +## Create a test repository + +First, I'll create a new folder in which I'll create my test project, and then +I'll create a repository for it. + +```bash +$ sudo mkdir ~/test +$ sudo svnadmin create /home/svn/test -m 'initial project structure' +``` + +This will create a new repository containing the base file structure. + +## Adding files into the test project + +```bash +$ cd ~/test
 +$ mkdir trunk tags branches +``` + +I can now import these new directories into the test repository. + +```bash +$ sudo svn import ~/test file:///home/svn/test -m 'Initial project directories' +``` + +This both adds and commits these new directories into the repository. + +In order for Apache to access the SVN repositories, the `/home/svn` directory +needs to be owned by the same user and group that Apache runs as. In Ubuntu, +this is usually www-data. To change the owner of a directory, use the chown +command. + +```bash +$ sudo chown -R www-data:www-data /home/svn +``` + +## Configuring Apache + +The first thing that I need to do is enable the dav_svn Apache module, using the +a2enmod command. + +```bash +$ sudo a2enmod dav_svn +``` + +With this enabled, now I need to modify the Apache configuration file. + +```bash +$ cd /etc/apache2 +$ sudo nano apache2.conf +``` + +At the bottom of the file, add the following lines, and then save the file by +pressing Ctrl+X. + +``` + + DAV svn + SVNParentPath /home/svn + +``` + +With this saved, restart the Apache service for the changes to be applied. + +```bash +sudo service apache2 restart +``` + +I can now browse through my test repository by opening Firefox, and navigating +to `http://127.0.0.1/svn/test`. Here, I can now see my three directories, +although they are currently all empty. + +## Securing my SVN repositories + +Before I start committing any files to the test repository, I want to ensure +that only authorised users can view it - currently anyone can view the +repository and it's contents, as well as being able to checkout and commit +files. To do this, I'm going to require the user to enter a username and a +password before viewing or performing any actions with the repository. + +Re-open apache2.conf, and replace the SVN Location information with this: + +``` + + DAV svn + SVNParentPath /home/svn + AuthType Basic + AuthName "My SVN Repositories" + AuthUserFile /etc/svn-auth + Require valid-user + +``` + +Now I need to create the password file. + +```bash +$ htpasswd -cm /etc/svn-auth oliver +``` + +I'm prompted to enter and confirm my password, and then my details are saved. +The Apache service will need to be restarted again, and then the user will need +to authenticate themselves before viewing the repositories. + +## Checking out the repository and commiting files + +For example, now want to checkout the files within my repository into a new +directory called 'test2' within my home directory. Firstly, I need to create the +new directory, and then I can issue the checkout command. + +```bash +$ cd ~ +$ mkdir test2 +$ svn checkout http://127.0.0.1/svn/test/trunk test2 +``` + +I'm passing the command two arguments - the first is the URL of the repository's +trunk directory, and the second is the directory where the files are to be +placed. As no files have been commited yet into the trunk, it appears to be +empty - but if you perform an ls -la command, you'll see that there is a hidden +.svn directory. + +Now you can start adding files into the directory. Once you've created your +files, perform a svn add command, passing in individual filenames as further +arguments. + +```bash +$ svn add index.php +$ svn add * +``` + +With all the required files added, they can be committed using +`svn commit -m 'commit message'` command, and the server can be updated using +the svn up command. diff --git a/source/_posts/how-put-your-php-application-subdirectory-another-site-nginx.md b/source/_posts/how-put-your-php-application-subdirectory-another-site-nginx.md new file mode 100644 index 00000000..53bdf7f4 --- /dev/null +++ b/source/_posts/how-put-your-php-application-subdirectory-another-site-nginx.md @@ -0,0 +1,29 @@ +--- +title: How to put your PHP application in a subdirectory of another site with Nginx +date: 2018-03-12 +excerpt: How to configure Nginx to serve a PHP application from within a subdirectory of another. +tags: + - nginx + - php +--- + +In January, [Chris Fidao][0] posted a video to [Servers for Hackers][1] showing +how to put different PHP applications in different subdirectories and have them +serving on different paths with Nginx. I’ve had to do this a few times +previously, and it’s great to have this video as a reference. + +> In this video, we work through how to put your PHP application in a +> subdirectory of another site. +> +> For example, we may have an application running at example.org but need a +> second application running at example.org/blog. +> +> This feels like it should be simple, but it turns out to be more complex and +> fraught with confusing Nginx configurations! To make matter worse (or, +> perhaps, to illustrate this point), a quick Google search reveals a TON of +> confusing, non-working examples. + + + +[0]: https://twitter.com/fideloper +[1]: https://serversforhackers.com diff --git a/source/_posts/how-run-drupal-8-phpunit-tests-within-docksal-phpstorm.md b/source/_posts/how-run-drupal-8-phpunit-tests-within-docksal-phpstorm.md new file mode 100644 index 00000000..f9a1af14 --- /dev/null +++ b/source/_posts/how-run-drupal-8-phpunit-tests-within-docksal-phpstorm.md @@ -0,0 +1,217 @@ +--- +title: How to run Drupal 8 PHPUnit Tests within Docksal from PhpStorm +date: 2018-07-19 +excerpt: How to configure PhpStorm to run automated tests within Docksal. +tags: + - docksal + - drupal + - drupal-8 + - phpstorm + - phpunit + - testing +promoted: true +--- + +I’ve recently re-watched [A Clean PHPUnit Workflow in PHPStorm][0] on +[Laracasts][1], where Jeffrey configures PhpStorm to run tests from within the +IDE. With Drupal 8 using PHPUnit too, I decided to try and do the same with a +local D8 site. + +Though because I’m using [Docksal][4] for my local development environment +which, at least on a Mac, runs Docker containers within a virtual machine, there +were some additional steps needed to achieve this and to have the tests run +within the Docksal virtual machine and using the correct containers. + +In this post, I’ll be using my [Drupal Testing Workshop codebase][2] as an +example, which is based on the [Drupal Composer project][3] with some +pre-configured Docksal configuration. + +This post is separated into a few different sections: + +- [Allow PhpStorm to connect to the CLI container](#allow-phpstorm-to-connect-to-the-cli-container) +- [Add a new deployment server](#add-a-new-deployment-server) +- [Configure PHP interpreter](#configuring-the-php-interpreter) +- [Set up PHPUnit in PhpStorm](#set-up-phpunit-in-phpstorm) +- [Running tests](#running-tests) + +## Allow PhpStorm to connect to the CLI container + +The first thing to do is to allow PhpStorm to connect to Docksal’s CLI container +to allow it to run the tests. We can do this by exposing the container’s SSH +port so that it’s available to the host machine and PhpStorm. + +As this is going to be unique to my environment, I’m going to add this to +`.docksal/docksal-local.yml` which I have in `.gitignore`, rather than +committing it into the repository and enforcing the same port number for +everyone else and potentially causing conflicts. + +In this case I’ll expose port 22 in the container to port 2225 locally. + +``` +version: '2.1' + +services: + cli: + ports: + - '2225:22' +``` + +Once added, run `fin start` to rebuild the project’s containers. + +You can verify the change by running `fin ps` and you should see something like +`0.0.0.0:2225->22/tcp` under Ports for the CLI container. + +## Add a new Deployment server + +Now PhpStorm can connect to Docksal, I can configure it to do so by adding a new +deployment server. + +- Open PhpStorm’s preferences, and go to 'Build, Execution, Deployment' and + 'Deployment'. +- Click 'Add' to configure a new deployment server. +- Enter a name like 'Docksal', and select SFTP as the server type. + +![Adding a new deployment server](/images/blog/phpstorm-phpunit-docksal/deployment-1.png){.with-border +.sm:max-w-sm} + +### Connection settings + +On the Connection tab: + +- Enter your domain name - e.g. `drupaltest.docksal` as the SFTP host. This will + resolve to the correct local IP address. +- Enter the exposed port for the CLI container that was entered in the previous + step. +- Enter "docker" as both the username and password. + +You should now be able to click "Test SFTP connection" and get a successfully +connected confirmation message. + +![Configuring a new deployment server](/images/blog/phpstorm-phpunit-docksal/deployment-2.png) + +### Mapping settings + +On the Mappings tab, add `/var/www` as the deployment path so that PhpStorm is +looking in the correct place for the project code. + +![Add mappings to the deployment server](/images/blog/phpstorm-phpunit-docksal/deployment-3.png){.with-border} + +## Configuring the PHP Interpreter + +In Preferences, search for 'PHP' within 'Languages & Frameworks', and add a new +CLI interpreter. + +![The PHP preferences in PhpStorm](/images/blog/phpstorm-phpunit-docksal/cli-interpreter-1.png){.with-border} + +In this case I’ve called it 'Docksal PHP 7.1', used the Docksal deployment +configuration, and set the path to the PHP executable to `/usr/local/bin/php` +(the same path that we would get if we ran `fin run which php`). You should see +both the deployment host URL displayed as well as the remote PHP version and +configuration filenames. + +![Configuring a new CLI interpreter](/images/blog/phpstorm-phpunit-docksal/cli-interpreter-2.png){.with-border} + +This can now be selected as the CLI interpreter for this project. + +![Selecting the new CLI interpreter in the PHP preferences](/images/blog/phpstorm-phpunit-docksal/cli-interpreter-3.png){.with-border} + +## Set up PHPUnit in PhpStorm + +In Preferences, search for 'Test Frameworks' and add a new framework. + +![Adding a new test framework (PHPUnit) in PHPStorm](/images/blog/phpstorm-phpunit-docksal/phpunit-1.png){.with-border} + +Select 'PHPUnit by Remote Interpreter' and then the 'Docksal PHP 7.1' that we +created in the last step. + +Select 'Use Composer autoloader' for the PHPUnit library setting so that +PhpStorm uses the version required by Drupal core, and set the path to +`/var/www/vendor/autoload.php`. + +Also specify the path to the default (phpunit.xml) configuration file. This will +depend on how your project is structured, in this case it’s at +`/var/www/web/core/phpunit.xml`. + +![Configuring PHPUnit in PHPstorm](/images/blog/phpstorm-phpunit-docksal/phpunit-4.png){.with-border} + +## Running tests + +With PHPUnit configured, next to each test class and method, you can see a green +circle (or a red one if the test failed the last run). You can click the circle +and select to run that test class or method. You can also right-click +directories in the project sidebar to run all of the tests within that +directory. + +![Running a test within PhpStorm](/images/blog/phpstorm-phpunit-docksal/running-tests-1.png){.with-border} + +When the tests start running, a new tool window will open that shows you all of +the selected tests, how long each test took to run and whether it passed or +failed. You can also see the CLI output from PHPUnit itself next to it. + +![The tests results being displayed](/images/blog/phpstorm-phpunit-docksal/running-tests-2.png){.with-border} + +From here, you also have the ability to re-run all of the tests, as well as a +single test method or a specific test class. + +Any test failures are shown here too, and for some failures like differences +between two arrays you can use PhpStorm’s internal comparison tools to view the +difference rather than needing to do so on the command line. + +![Showing a failing test](/images/blog/phpstorm-phpunit-docksal/test-failure-1.png){.with-border} + +![Displaying the difference between two arrays](/images/blog/phpstorm-phpunit-docksal/test-failure-2.png){.with-border +.sm:max-w-md} + +### Keyboard shortcuts + +As per the video, I’ve also added some keyboard shortcuts to my keymap, so I can +press ⌘T to run the current test method or class that I’m in, and ⇧⌘T to re-run +the last test. + +![Adding a keyboard shortcut to run the current test](/images/blog/phpstorm-phpunit-docksal/keyboard-shortcuts-1.png){.with-border} + +![Adding a keyboard shortcut to re-run the last test](/images/blog/phpstorm-phpunit-docksal/keyboard-shortcuts-2.png){.with-border} + +### Database issues + +When running functional tests that require a database, I was getting a database +error like the one below: + +> Drupal\Core\Installer\Exception\InstallerException : Resolve all issues below +> to continue the installation. For help configuring your database server, see +> the installation +> handbook, or contact your hosting provider. + +In `settings.php`, I check for the presence of `/.dockerenv` to ensure that +we’re inside a Docker container, as well as the presence of a +`docksal.settings.yml` file. The latter contains the database credentials for +Drupal to connect to the MySQL database. + +```php +if (file_exists('/.dockerenv') && file_exists(__DIR__ . '/docksal.settings.php')) { + include __DIR__ . '/docksal.settings.php'; +} +``` + +In order to get the tests to run, I had to prevent this file from being loaded +during the tests. I can do this by checking that `SIMPLETEST_DB`, an environment +variable set in phpunit.xml is not present. + +```php +// settings.php + +if (file_exists('/.dockerenv') && file_exists(__DIR__ . '/docksal.settings.php') && !getenv('SIMPLETEST_DB')) { + include __DIR__ . '/docksal.settings.php'; +} +``` + +With this extra condition, the database credentials are loaded correctly and the +functional tests run properly. + +Happy testing! + +[0]: https://laracasts.com/series/php-bits/episodes/2 +[1]: https://laracasts.com +[2]: https://github.com/opdavies/drupal-testing-workshop +[3]: https://github.com/drupal-composer/drupal-project +[4]: https://docksal.io diff --git a/source/_posts/how-use-environment-variables-your-drupal-settings-docksal.md b/source/_posts/how-use-environment-variables-your-drupal-settings-docksal.md new file mode 100644 index 00000000..54b4431c --- /dev/null +++ b/source/_posts/how-use-environment-variables-your-drupal-settings-docksal.md @@ -0,0 +1,92 @@ +--- +title: How to Use Environment Variables for your Drupal Settings with Docksal +date: 2018-06-04 +excerpt: How to leverage environment variables with Drupal and Docksal. +tags: + - docksal + - drupal + - drupal-planet +--- + +Within the [Docksal documentation for Drupal settings][0], the example database +settings include hard-coded credentials to connect to the Drupal database. For +example, within a `settings.php` file, you could add this: + +```php +$databases['default']['default'] = [ + 'driver' => 'mysql', + 'host' => 'db', + 'database' => 'myproject_db', + 'username' => 'myproject_user', + 'password' => 'myproject_pass', +]; +``` + +Whilst this is fine, it does mean that there is duplication in the codebase as +the database credentials can also be added as environment variations within +`.docksal/docksal.env` - this is definitely the case if you want to use a custom +database name, for example. + +Also if one of these values were to change, then Drupal wouldn't be aware of +that and would no longer be able to connect to the database. + +It also means that the file can’t simply be re-used on another project as it +contains project-specific credentials. + +We can improve this by using the environment variables within the settings file. + +The relevant environment variables are `MYSQL_DATABASE` for the database name, +and `MYSQL_USER` and `MYSQL_PASSWORD` for the MySQL username and password. These +can be set in `.docksal/docksal.env`, and will need to be present for this to +work. + +For example: + +``` +DOCKSAL_STACK=default +MYSQL_DATABASE=myproject_db +MYSQL_USER=myproject_user +MYSQL_PASSWORD=myproject_pass +``` + +With these in place, they can be referenced within the settings file using the +`getenv()` function. + +``` +$databases['default']['default'] = [ + 'driver' => 'mysql', + 'host' => 'db', + 'database' => getenv('MYSQL_DATABASE'), + 'username' => getenv('MYSQL_USER'), + 'password' => getenv('MYSQL_PASSWORD'), +]; +``` + +Now the credentials are no longer duplicated, and the latest values from the +environment variables will always be used. + +However, you may see a message like this when you try and load the site: + +> Drupal\Core\Database\DatabaseAccessDeniedException: SQLSTATE[HY000][1045] +> Access denied for user ''@'172.19.0.4' (using password: NO) in +> /var/www/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php on line 156 + +If you see this, the environment variables aren’t being passed into Docksal’s +`cli` container, so the values are not being populated. To enable them, edit +`.docksal/docksal.yml` and add `MYSQL_DATABASE`, `MYSQL_PASSWORD` and +`MYSQL_USER` to the `environment` section of the `cli` service. + +```yaml +version: '2.1' +services: + cli: + environment: + - MYSQL_DATABASE + - MYSQL_PASSWORD + - MYSQL_USER +``` + +After changing this file, run `fin start` to rebuild the project containers and +try to load the site again. + +[0]: https://docksal.readthedocs.io/en/master/advanced/drupal-settings diff --git a/source/_posts/ignoring-phpcs-sniffs-phpunit-tests.md b/source/_posts/ignoring-phpcs-sniffs-phpunit-tests.md new file mode 100644 index 00000000..d5ec3334 --- /dev/null +++ b/source/_posts/ignoring-phpcs-sniffs-phpunit-tests.md @@ -0,0 +1,77 @@ +--- +title: Ignoring PHPCS sniffs for PHPUnit tests +excerpt: How to exclude certain PHPCS sniffs within your PHPUnit tests, so that you can write your tests methods how you'd like without getting coding standards errors. +tags: + - drupal + - drupal-planet + - php + - phpunit +date: 2021-01-04 +--- + +**Note:** This post is written with a Drupal context, but applies to any PHP project. + +This is a test that I wrote recently, which uses the camel case method name that is recommended by the Drupal and PSR-2 coding standards: + +```php +public function testThatPathAliasesAreNotTransferredToTheNewLanguageWhenOneIsAdded(): void { + // ... +} +``` +It has a long method name that describes the test that is being run. However, it's quite hard to read. Generally, I prefer to write tests like this, using the `@test` annotation (so that I can remove the `test` prefix) and snake case method names: + +```php +/** @test */ +public function path_aliases_are_not_transferred_to_the_new_language_when_one_is_added(): void { + // ... +} +``` + +This to me is a lot easier to read, particularly for long and descriptive test method names, and is commonly used within parts of the PHP community. + +This approach, however, can result in some errors from PHPCS: + +- The open comment tag must be the only content on the line +- Public method name "DefinedLanguageNodeTest::path_aliases_are_not_transferred_to_the_new_language_when_one_is_added" is not in lowerCamel format + +We can avoid the errors by excluding the files when running PHPCS, or modifying rules within phpcs.xml (or phpcs.xml.dist) file to change the severity value for the rules. These approaches would mean either ignoring all PHPCS sniffs within the test files or ignoring some checks within all files, neither of which is an ideal approach. + +## Ignoring whole or partial files + +We can tell PHPCS to ignore whole or partial files by adding comments - there's [an example of this](https://git.drupalcode.org/project/drupal/-/blob/ad34608ab0bb115c53f4aaa0573c30dd8dc5b23a/sites/default/default.settings.php#L3 "Drupal's default.settings.php file with a 'coding standards ignore' comment") at the top of `default.settings.php` file: + +```php +// @codingStandardsIgnoreFile +``` + +The `@codingStandards` syntax, however, is deprecated and will be removed in PHP_CodeSniffer version 4.0. The new syntax to do this is: + +```php +// phpcs:ignoreFile +``` + +As well as `phpcs:ignoreFile` which ignores all of the sniffs in an entire file, there are also commands to disable and re-enable PHPCS at different points within the same file: + +```php +// Stop PHPCS checking. +// phpcs:disable + +// Start PHPCS checking. +// phpcs:enable +``` + +## Disabling specific rules in a file + +As well as excluding a section of code from checks, with `phpcs:ignore` you can also specify a list of sniffs to ignore. For example: + +```php +// phpcs:disable Drupal.Commenting.DocComment, Drupal.NamingConventions.ValidFunctionName +``` + +By adding this to the top of the test class, these specific sniffs will be ignored so no errors will be reported, and any other sniffs will continue to work as normal. + +If you're unsure what the names of the sniffs are that you want to ignore, add `-s` to the PHPCS command to have it include the sniff names in its output. + +For more information on ignoring files, folders, part of files, and limiting results, see the [Advanced Usage page for the PHP CodeSniffer project](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage) on GitHub. + +You can also see this being used in [some of the tests for this website](https://github.com/opdavies/oliverdavies-uk/tree/production/web/modules/custom/blog/tests/src/Kernel). diff --git a/source/_posts/imagefield-import-archive.md b/source/_posts/imagefield-import-archive.md new file mode 100644 index 00000000..2a121cc7 --- /dev/null +++ b/source/_posts/imagefield-import-archive.md @@ -0,0 +1,35 @@ +--- +title: Imagefield Import Archive +date: 2011-05-23 +excerpt: I've finally uploaded my first module onto Drupal.org! +tags: + - drupal-planet + - imagefield-import +--- + +I've finally uploaded my first module onto Drupal.org! + +I've written many custom modules, although the vast majority of them are either +small tweaks for my own sites, or company/site-specific modules that wouldn't be +good to anyone else, so there would be nothing achieved by contributing them +back to the community. Previously, I've blogged about the +[Imagefield Import](http://drupal.org/project/imagefield_import) module - a +module that I use on a number of sites, both personal and for clients - and what +I've looked for lately is for a way to speed up the process again. Gathering my +images together and manually copying them into the import directory takes time - +especially if I'm working somewhere with a slow Internet connection and I'm +FTP-ing the images into the directory. Also, it's not always the easiest +solution for site users - especially non-technical ones. + +So, I wrote the Imagefield Import Archive module. Including comments, the module +contains 123 lines, and builds upon the existing functionality of the Imagefield +Import module by adding the ability for the user to upload a .zip archive of +images. The archive is then moved into the specified import directory and +unzipped before being deleted, and the user is directed straight to the standard +Imagefield Import page where their images are waiting to be imported, just as +usual. + +The module is currently a +[sandbox project](http://drupal.org/sandbox/opdavies/1165110) on Drupal.org, +although I have applied for full project access so that I can be added as a +fully-fledged downloadable module. diff --git a/source/_posts/improve-jpg-quality-imagecache-and-imageapi.md b/source/_posts/improve-jpg-quality-imagecache-and-imageapi.md new file mode 100644 index 00000000..2fc17e93 --- /dev/null +++ b/source/_posts/improve-jpg-quality-imagecache-and-imageapi.md @@ -0,0 +1,25 @@ +--- +title: Improve JPG Quality in Imagecache and ImageAPI +date: 2010-06-02 +excerpt: How to fix the quality of uploaded images in Drupal. +tags: + - drupal-planet + - drupal-6 + - imagecache +--- + +Whilst uploading images for my Projects and Testimonials sections, I noticed +that the Imagecache-scaled images weren't as high a quality the originals on my +Mac. I did some searching online and found out that, by default, Drupal +resamples uploaded jpgs to 75% of their original quality. + +To increase the quality of your images, change the setting in the two following +places: + +- admin/settings/imageapi/config +- admin/settings/image-toolkit + +The first one is for ImageAPI. Primarily, this means Imagecache presets. The +second one is for core's image.inc. This is used for resizing profile pictures +in core, and some contrib modules. Once changed, I did have to flush each of the +Imagecache presets (admin/dist/imagecache) for the changes to take effect. diff --git a/source/_posts/include-css-fonts-using-sass-each-loop.md b/source/_posts/include-css-fonts-using-sass-each-loop.md new file mode 100644 index 00000000..f3e07f3d --- /dev/null +++ b/source/_posts/include-css-fonts-using-sass-each-loop.md @@ -0,0 +1,67 @@ +--- +title: Include CSS Fonts by Using a SASS each Loop +date: 2014-11-18 +excerpt: How to use an SASS each loop to easily add multiple fonts to your CSS. +tags: + - compass + - drupal-planet + - fonts + - sass +--- + +How to use an @each loop in SASS to quickly include multiple font files within +your stylesheet. + +Using a file structure similar to this, organise your font files into +directories, using the the font name for both the directory name and for the +file names. + +```bash +. +├── FuturaBold +│ ├── FuturaBold.eot +│ ├── FuturaBold.svg +│ ├── FuturaBold.ttf +│ └── FuturaBold.woff +├── FuturaBoldItalic +│ ├── FuturaBoldItalic.eot +│ ├── FuturaBoldItalic.svg +│ ├── FuturaBoldItalic.ttf +│ └── FuturaBoldItalic.woff +├── FuturaBook +│ ├── FuturaBook.eot +│ ├── FuturaBook.svg +│ ├── FuturaBook.ttf +│ └── FuturaBook.woff +├── FuturaItalic +│ ├── FuturaItalic.eot +│ ├── FuturaItalic.svg +│ ├── FuturaItalic.ttf +│ └── FuturaItalic.woff +``` + +Within your SASS file, start an `@each` loop, listing the names of the fonts. In +the same way as PHP's `foreach` loop, each font name will get looped through +using the `$family` variable and then compiled into CSS. + +```scss +@each $family in FuturaBook, FuturaBold, FuturaBoldItalic, FuturaItalic { + @font-face { + font-family: #{$family}; + src: url('../fonts/#{$family}/#{$family}.eot'); + src: url('../fonts/#{$family}/#{$family}.eot?#iefix') format('embedded-opentype'), + url('../fonts/#{$family}/#{$family}.woff') format('woff'), + url('../fonts/#{$family}/#{$family}.ttf') format('truetype'), + url('../fonts/#{$family}/#{$family}.svg##{$family}') format('svg'); + font-weight: normal; + font-style: normal; + } +} +``` + +When the CSS has been compiled, you can then use in your CSS in the standard +way. + +```scss +font-family: "FuturaBook"; +``` diff --git a/source/_posts/include-environment-specific-settings-files-pantheon.md b/source/_posts/include-environment-specific-settings-files-pantheon.md new file mode 100644 index 00000000..237a248e --- /dev/null +++ b/source/_posts/include-environment-specific-settings-files-pantheon.md @@ -0,0 +1,100 @@ +--- +title: Include environment-specific settings files on Pantheon +date: 2014-11-27 +excerpt: How to load a different settings file per environment on Pantheon. +tags: + - drupal + - drupal-planet + - pantheon + - settings.php +--- + +I was recently doing some work on a site hosted on +[Pantheon](http://getpantheon.com) and came across an issue, for which part of +the suggested fix was to ensure that the `$base_url` variable was explicitly +defined within settings.php (this is also best practice on all Drupal sites). + +The way that was recommended was by using a `switch()` function based on +Pantheon's environment variable. For example: + +```php +switch ($_SERVER['PANTHEON_ENVIRONMENT']) { + case 'dev': + // Development environment. + $base_url = 'dev-my-site.gotpantheon.com'; + break; + + + case 'test': + // Testing environment. + $base_url = 'test-my-site.gotpantheon.com'; + break; + + + case 'live': + // Production environment. + $base_url = 'live-my-site.gotpantheon.com'; + break; +} +``` + +Whilst this works, it doesn't conform to the DRY (don't repeat yourself) +principle and means that you also might get a rather long and complicated +settings file, especially when you start using multiple switches and checking +for the value of the environment multiple times. + +My alternative solution to this is to include an environment-specific settings +file. + +To do this, add the following code to the bottom of settings.php: + +```php +if (isset($_SERVER['PANTHEON_ENVIRONMENT'])) { + if ($_SERVER['PANTHEON_ENVIRONMENT'] != 'live') { + // You can still add things here, for example to apply to all sites apart + // from production. Mail reroutes, caching settings etc. + } + + // Include an environment-specific settings file, for example + // settings.dev.php, if one exists. + $environment_settings = __DIR__ . '/settings.' . $_SERVER['PANTHEON_ENVIRONMENT'] . '.php'; + if (file_exists($environment_settings)) { + include $environment_settings; + } +} +``` + +This means that rather than having one long file, each environment has it's own +dedicated settings file that contains it's own additional configuration. This is +much easier to read and make changes to, and also means that less code is loaded +and parsed by PHP. Settings that apply to all environments are still added to +settings.php. + +Below this, I also include a +[similar piece of code](/blog/include-local-drupal-settings-file-environment-configuration-and-overrides/) +to include a settings.local.php file. The settings.php file then gets committed +into the [Git](http://git-scm.com) repository. + +Within the sites/default directory, I also include an example file +(example.settings.env.php) for reference. This is duplicated, renamed and +populated accordingly. + +```php +. This post was accurate at the time of +writing, whereas the documentation page will be kept up to date with any future +changes._ + +## Initial configuration + +### Download the Library + +The library can be downloaded directly from GitHub, and should be placed within +you _sites/all/libraries/nomensa_amp_ directory. + +```bash +drush dl libraries nomensa_amp +git clone https://github.com/nomensa/Accessible-Media-Player sites/all/libraries/nomensa_amp +cd sites/all/libraries/nomensa_amp +rm -rf Accessible-media-player_2.0_documentation.pdf example/ README.md +drush en -y nomensa_amp +``` + +### Configure the Module + +Configure the module at admin/config/media/nomensa-amp and enable the +players that you want to use. + +## Adding videos + +Within your content add links to your videos. For example: + +### YouTube + +```html +Checking colour contrast +``` + +### Vimeo + +```html +Screen readers are strange, when you're a stranger by Leonie Watson +``` + +## Adding captions + +The best way that I can suggest to do this is to use a File field to upload your +captions file: + +1. Add a File field to your content type; +1. On your page upload the captions file. +1. Right-click the uploaded file, copy the link location, and use this for the + path to your captions file. + +For example: + +```html +Checking colour contrast Captions for Checking Colour Contrast +``` + +## Screencast + +
+ +
diff --git a/source/_posts/installing-nagios-centos.md b/source/_posts/installing-nagios-centos.md new file mode 100644 index 00000000..75bf0170 --- /dev/null +++ b/source/_posts/installing-nagios-centos.md @@ -0,0 +1,15 @@ +--- +title: Installing Nagios on CentOS +date: 2012-04-17 +excerpt: How to install Nagios on CentOS. +tags: + - nagios + - centos + - linux +--- + +A great post details that details the steps needed to install +[Nagios](http://nagios.org) - a popular open source system and network +monitoring software application - on CentOS. + + diff --git a/source/_posts/interview-drupal-expert-code-enigma.md b/source/_posts/interview-drupal-expert-code-enigma.md new file mode 100644 index 00000000..e4063d1e --- /dev/null +++ b/source/_posts/interview-drupal-expert-code-enigma.md @@ -0,0 +1,13 @@ +--- +title: Interview with a Drupal Expert (with Code Enigma) +excerpt: I recently did an interview with Code Enigma for their blog. +tags: + - drupal + - interview + - personal +date: 2020-08-31 +--- + +I recently did an interview with Drupal and PHP agency [Code Enigma](https://www.codeenigma.com) for their blog, in which we talked about getting started in the Drupal community, [working for 10 years full-time with Drupal and PHP](/blog/10-years-working-full-time-drupal-php), companies adopting open source technologies, and my favourite Drupal events. + +To read it, go to [the Code Enigma blog](https://blog.codeenigma.com/interview-with-a-drupal-expert-9fcd8e0fad28 "'Interview with a Drupal Expert' on the Code Enigma blog"). diff --git a/source/_posts/introducing-drupal-distribution-meetups.md b/source/_posts/introducing-drupal-distribution-meetups.md new file mode 100644 index 00000000..f796a766 --- /dev/null +++ b/source/_posts/introducing-drupal-distribution-meetups.md @@ -0,0 +1,29 @@ +--- +title: Introducing a Drupal distribution for meetup websites +excerpt: I'm starting development on a new Drupal distribution for building meetup group websites. +tags: + - drupal + - drupal-9 + - drupal-distribution + - drupal-meetup-distribution + - personal + - php + - php-south-wales +date: 2021-10-07 +--- + +I'm the current organiser of the [PHP South Wales user group](https://www.phpsouthwales.uk) and built the current website with Drupal 8, which I started in 2019. + +There are some basic pages, but also functionality to display upcoming and past events, show current sponsors, and to populate event data from Meetup.com - functionality that could needed by other meetup groups for their websites - such as other PHP and Drupal user groups that I've organised and attended. + +Inspired by other Drupal distributions like [LocalGov](https://www.drupal.org/project/localgov), I've decided to refactor the current site into a reusable distribution that other meetup groups can use. It's not intended to be a clone of Meetup.com, but to be used for a website for a single meetup group to show their events and showcase their own community. + +This also means that any new functionality can be added straight to the distribution and immediately available for everyone. + +I've created a [project page on Drupal.org][drupalorg] and a [Drupal Meetup organisation on GitHub][github] which contains repositories for the distribution as well as a project template that are pushed to [Packagist][packagist] to that they can be installed with Composer - e.g. `composer create-project --stability dev drupal-meetup/drupal-meetup-project my-new-meetup`. + +This seems like a good opportunity to do some more Drupal contribution and may benefit others too who want to build their own meetup group websites. + +[drupalorg]: https://www.drupal.org/project/meetup +[github]: https://github.com/drupal-meetup +[packagist]: https://packagist.org/packages/opdavies/?query=drupal-meetup diff --git a/source/_posts/introducing-the-drupal-meetups-twitterbot.md b/source/_posts/introducing-the-drupal-meetups-twitterbot.md new file mode 100644 index 00000000..cf12e4c1 --- /dev/null +++ b/source/_posts/introducing-the-drupal-meetups-twitterbot.md @@ -0,0 +1,29 @@ +--- +title: Introducing the Drupal Meetups Twitterbot +date: 2017-06-09 +excerpt: I’ve written a twitterbot for promoting Drupal meetups. +tags: + - php + - twitter +--- + +

![](/images/blog/drupal-meetups-twitterbot.png)

+ +The [Drupal Meetups Twitterbot][0] is a small project that I worked on a few +months ago, but hadn't got around to promoting yet. It’s intention is to provide +[one Twitter account][1] where people can get the up to date news from various +Drupal meetups. + +It works by having a whitelist of [Twitter accounts and hashtags][2] to search +for, uses [Codebird][3] to query the Twitter API and retweets any matching +tweets on a scheduled basis. + +If you would like your meetup group to be added to the list of searched +accounts, please [open an issue][4] on the GitHub repo. + +[0]: https://github.com/opdavies/drupal-meetups-twitterbot +[1]: https://twitter.com/drupal_meetups +[2]: + https://github.com/opdavies/drupal-meetups-twitterbot/blob/master/bootstrap/config.php +[3]: https://www.jublo.net/projects/codebird/php +[4]: https://github.com/opdavies/drupal-meetups-twitterbot/issues/new diff --git a/source/_posts/leaving-nomensa-joining-precedent.md b/source/_posts/leaving-nomensa-joining-precedent.md new file mode 100644 index 00000000..a5b3c45b --- /dev/null +++ b/source/_posts/leaving-nomensa-joining-precedent.md @@ -0,0 +1,32 @@ +--- +title: Leaving Nomensa, Joining Precedent +date: 2013-04-20 +excerpt: Yesterday was my last day working at Nomensa. Next week, I'll be starting as a Senior Developer at Precedent. +tags: + - nomensa + - personal + - precedent +--- + +Yesterday was my last day working at +[Nomensa](http://www.nomensa.com 'Nomensa'). Next week, I'll be starting as a +Senior Developer at [Precedent](http://www.precedent.co.uk 'Precedent'). + +The last 14 months that I've been working at Nomensa have been absolutely +fantastic, and had allowed me to work on some great projects for great clients - +mainly [unionlearn](http://www.unionlearn.org 'unionlearn') and +[Digital Theatre Plus](http://www.digitaltheatreplus.com 'Digital Theatre Plus'). +I've learned so much about accessibility and web standards, and have pretty much +changed my whole approach to front-end development to accommodate best +practices. I've also been involved with the Drupal Accessibility group since +starting at Nomensa, and have written several accessibility-focused Drupal +modules, including the +[Nomensa Accessible Media Player](http://drupal.org/project/nomensa_amp 'The Nomensa Accessible Media Player Drupal module') +module and the +[Accessibility Checklist](http://drupal.org/project/a11y_checklist 'The accessibility checklist for Drupal'). +I'll definitely be continuing my interest in accessibility, championing best +practices, and incorporating it into my future work wherever possible. + +With that all said, I'm really looking forward to starting my new role at +Precedent, tackling some new challenges, and I'm sure that it'll be as great a +place to work as Nomensa was. diff --git a/source/_posts/live-blogging-symfonylive-london-2019.md b/source/_posts/live-blogging-symfonylive-london-2019.md new file mode 100644 index 00000000..1cdc3a9a --- /dev/null +++ b/source/_posts/live-blogging-symfonylive-london-2019.md @@ -0,0 +1,713 @@ +--- +title: Live Blogging From SymfonyLive London 2019 +date: 2019-09-13 +tags: + - conference + - php + - symfony + - symfonylive +--- + +Inspired by [Matt Stauffer](https://twitter.com/stauffermatt)'s +[live blogging of the keynote](https://mattstauffer.com/blog/introducing-laravel-vapor) +at Laracon US, I’m going to do the same for the sessions that I’m attending at +[SymfonyLive London 2019](https://london2019.live.symfony.com)... + +## Keynote (Back to the basics) + +**Embrace the Linux philosophy** + +- How we grow the Symfony ecosystem. Built abstracts. +- HttpFoundation, HttpKernel +- Moved to infrastructure +- A few abstractions on top of PHP. Improved versions of PHP functions (`dump` + and `var_dump`) +- Started a add higher level abstractions (e.g. Mailer), built on the lower + ones. +- Recently worked on PHPUnit assertions. Mailer in Symony 4.4. Can test if an + email is sent or queued + +**Building flexible high-level abstractions on top of low-level ones** + +### What's next? + +- Mailer announced in London last year. New component. +- System emails? e.g. new customer, new invoice. +- Symfony Mailer = Built-in responsive, flexible, and generic system emails + - Twig with TwigExtraBundle + - Twig `inky-extra` package (Twig 1.12+) + - Zurb Foundation for Emails CSS stylesheet + - Twig `cssinliner-extra` package (Twig 1.12+) + - Optimised Twig layouts +- `SystemEmail` class extends templated email +- Can set importance, +- Customisable +- Always trying to keep flexible, so things can be overidden and customised + +### Sending SMS messages + +- new `Texter` and `SmsMessage` class for sending SMS messages +- Same abstraction as emails, but for SMS messages +- Based on HttpClient + Symfony Messenger and third-party providers (Twilio and + Nexmo) `twilio://` and `nemxo://` +- Can set via transport `$sms->setTransport('nexmo')` +- Extend the `SystemEmail` and do what you want +- Failover + +### Sending Messages + +- Create `ChatMessage` +- Telegram and Slack +- `$message->setTransport('telegram')`, `$bus->dispatch($message)` +- Send to Slack **and** Telegram +- `SlackOptions` and `TelegramOptions` for adding emojis etc +- Common transport layer `TransportInterface`, `MessageInterface` +- Failover - e.g. if Twilio is down, send to Telegram + +### New component - SymfonyNotifier + +- Channels - email, SMS, chat +- Transport, slack, telegram, twilio +- Create a notification, arguments are message and transports (array) +- Receiver +- Customise notifications, `InvoiceNotification` extends `Notification`. + `getChannels` + - Override default rendering + - `ChatNotificationInterface` - `asChatMessage()` +- Semantic configuration + - `composer req twilio-notifier telegram-notifier` +- Channels + - Mailer + - Chatter + - Texter + - Browser + - Pusher (iOS, Android, Desktop native notifications) + - Database (web notification centre) + - **A unified way to notify Users via a unified Transport layer** +- Each integration is only 40 lines of code + +### What about a SystemNotification? + +- Autoconfigured channels +- `new SystemNotification`, `Notifier::getSystemReceivers` +- Importance, automatically configures channels +- Different channels based on importance +- `ExceptionNotification` - get email with stack trace attached + +Notifier + +- send messages via a unified api +- send to one or many receivers +- Default configu or custom one + +### How can we leverage this new infrastructure? + +- `Monolog NotifierHandler` - triggered on `Error` level logs +- Uses notified channel configuration +- Converts Error level logs to importance levels +- Configurablelike other Notifications +- 40 lines of code +- Failed Messages Listener - 10 lines of glue code + +- **Experimental component in 5.0** +- Can't in in 4.4 as it's a LTS version +- First time an experimental component is added +- Stable in 5.1 + +## Queues, busses and the Messenger component (Tobias Nyholm) + +- Stack is top and buttom - Last-in, first-out +- Queue is back and front - last in, first out + +### 2013 + +- Using Symfony, used 40 or 50 bundles in a project - too much information! +- Used to copy and paste, duplicate a lot of code +- Testing your controllers - controllers as services? +- Controllers are 'comfortable' +- Tried adding `CurrentUserProvider` service to core, should be passed as an + argument. Cannot test. +- 'Having Symfony all over the place wasn't the best thing' - when to framework + (Matthias Noback) + - Hexagonal architecture + - Keep your kernel away from infrastructure. Let the framework handle the + infrastructure. +- Controller -> Command -> Command Bus -> `CommandHandler` + +#### What did we win? + +- Can leverage Middleware with a command bus +- Queues as a service (RabbitMQ) +- Work queue - one producer, multiple consumers +- Queues should be durable - messages are also stored on disk, consumers should + acknowledge a message once a message is handled +- Publish/subscribe + - Producer -> Fanout/direct with routing (multiple queues) -> multiple + consumers +- Topics - wildcards + +### 2016 + +- New intern. Understand everything, 'just PHP'. Plain PHP application, not + 'scary Symfony' + +### Symfony Messenger + +- `composer req symfony/messager` - best MessageBus implementation +- Message -> Message bus -> Message handler +- Message is a plain PHP class +- Handler is a normal PHP class which is invokable +- `messenger:message_hander` tag in config +- Autowire with `MessageHandlerInterface` +- What if it takes 20 seconds to send a message? Use asynchronous. +- Transports as middleware (needs sender, receiver, configurable with DSN, + encode/decode). `MESSENGER_DSN` added to `.env` +- Start consumer with `bin/console messager:consume-messages`. Time limit with + `--time-limit 300` +- PHP Enqueue - production ready, battle-tested messaging solution for PHP + +### Issues + +- Transformers, takes an object and transforms into an array - + `FooTransformer implements TransformerInterface`. +- Don't break other apps by changing the payload. + +#### Multiple buses + +- Command bus, query bus, event bus +- Separate actions from reactions + +#### Envelope + +- Stamps for metadata - has the item been on the queue already? + +#### Failures + +- Requeue, different queue or same queue after a period of time +- Failed queue 1 every minute, failed queue 2 every hour - temporary glitches or + a bug? + +#### Creating entities + +- What if two users registered at the same tiem? Use uuids rather than IDs. +- Symfony validation - can be used on messages, not just forms. + +- Cache everything + + - Option 1: HTTP request -> Thin app (gets responses from Redis) -> POST to + queue. Every GET request would warm cache + - Option 2: HTTP request -> Thin app -> return 200 response -> pass to workers + +- Tip: put Command and CommandHandlers in the same directory + +## HttpClient (Nicolas Grekas) + +- new symfony component, released in may +- Httpclient contracts, separate package that contains interfaces + - Symfony + - PHP-FIG + - Httplug +- `HttpClient::create()`. `$client->get()` +- JSON decoded with error handling +- Used on symfony.com website (#1391). Replaces Guzzle `Client` for + `HttpClientInterface` +- Object is stateless, Guzzle is not. Doesn't handle cookies, cookies are state +- Remove boilerplate - use `toArray()` +- Options as third argument - array of headers, similar to Guzzle + +### What can we do with the Response? + +- `getStatusCode(): int` +- `getHeaders(): array` +- `getContent(): string` +- `toArray(): array` +- `cancel(): void` +- `getInfo(): array` - metadata +- Everything is lazy! +- 80% of use-cases covered + +### What about PSR-18? + +- Decorator/adapter to change to PSR compatible +- Same for Httplug + +### What about the remaining 20%? + +- Options are part of the abstraction, not the implementation + +#### Some of the options + +- `timeout` - control inactivity periods +- `proxy` - get through a http proxy +- `on_progress` - display a progress bar / build a scoped client +- `base_url` - resolve relative URLS / build a scoped client +- `resolve` - protect webhooks against calls to internal endpoints +- `max_redirects` - disable or limit redirects + +- Robust and failsafe by default + +- Streamable uploads - `$mimeParts->toIterable()`. +- donwload a file + + ```php + foreach ($client->stream($response) as $chunk) { + // ... + } + ``` + +* Responses are lazy, requests are concurrent +* Asychronus requests. Reading in network order + +``` +foreach ($client->stream($responses) as $response => $chunk) { + if ($chunk->isLast()) { + // a $response completed + } else { + // a $response's got network activity or timeout + } +} +``` + +- 379 request completed in 0.4s! +- `Stream` has second argument, max number of seconds to wait before yielding a + timeout chunk +- `ResponseInterface::getInfo()` - get response headers, redirect count and URL, + start time, HTTP method and code, user data and URL + - `getInfo('debug')` - displays debug information + +### The components + +- `NativeHttpClient` and `CurlHttpClient` + - both provide + - 100% contracts + - secure directs + - extended (time) info + - transparent HTTP compression and (de)chunking + - automatic HTTP proxy configuration via env vars + +#### `NativeHttpClient` + +- is most portable, works for everyone +- based on HTTP stream wrapper with fixed redirect logic +- blocking until response headers arrive + +#### `CurlHttpClient` + +- Requires ext-curl with fixed redirection logic +- Multiplexing response headers and bodies +- Leverages HTTP/2 and PUSH when available +- Keeps connections open also between synchronous requests, no DNS resolution so + things are faster + +#### Decorators + +- ScopingHttpClient - auto-configure options based on request URL +- MockHttpClient - for testing, doesn't make actual HTTP requests +- CachingHttpClient - adds caching on a HTTP request +- Psr18Client +- HttplugClient +- TraceableHttpClient + +### Combining + +#### FrameworkBundle/Autowiring + +```yaml +framework: + http_client: + max_host_connections: 4 + deault_options: + # .... + scoped_client: + # ... +``` + +#### HttpBrowser + +- HttpClient + DomCrawler + CssSelector + HttpKernel + BrowserKit +- RIP Goutte! + +### Coming in 4.4... + +- `max_duration` +- `buffer` based on a callable +- `$chunk->isInformational()` +- `$response->toStream()` +- Async-compatible extensibility, when decoration is not enough + +`composer req symfony/http-client` + +## Symfony Checker is coming (Valentine Boineau) + +- Static analysis tool for Symfony + - Does a method exist? + - Is it deprecated? +- insight.symfony.com +- @symfonyinsight +- Released soon + +### Differences + +- Specialise in Symfony - can see more relevant things +- Different interface to other services + +## Feeling unfulfilled by SPA promises? Go back to Twig (Dan Blows) + +A way on the front-end JS, CSS, images at the beginning of the request, sends a +HTTP request (XHR/AJAX) to the back-end + +### Why SPAs? + +- A way on the front-end JS, CSS, images at the beginning of the request, sends + a HTTP request (XHR/AJAX) to the back-end +- no full page refresh +- Supposed to be much quicker +- 'Right tool for the job' - JS on the front-end, PHP on the back-end +- Division of responsibility == faster development +- Reusable API - Api -> Mobile App and SPA - easy to add another consumer +- Easier to debug? + +### Why not SPAs? + +- Lots of HTTP requests (400 to load the initial page on one project) == slow + front end +- Blurred responsibilities == tightly coupled teams +- harder to debug, bugs fall between systems and teams. Huge gap between + front-end and back-end, passing responsibilites. +- You can fix these problems in SPAs, but is it worth it? + - Examples of good SPAs - Trello, Flickr + +### Using Twig as an alternative to an SPA? + +#### Faster UI - Try and figure out where the problem is. + +If you're trying to speed things up, find out where the problem is. + +- Browser tools +- Web Debug Toolbar +- Blackfire +- Optimise and monitor + +#### Speed up Twig + +- Speeding up Symfony +- ext/twig (PHP5 only, not PHP 7) +- Store compiled templates in Opcache, make sure it's enabled +- Render assets though the webserver (assetic not running all the time) + +#### Edge side includes + +- Component cached differently to the rest of the page +- Varnish/Nginx +- `render_esi` +- News block that caches frequently, rest of the page + +#### HTTP/2 with Weblink + +- slow finding CSS files to load - 'push' over CSS files, doesn't need to wait +- `preload()` - https://symfony.com/doc/current/web_link.html + +#### Live updating pages + +- Instantly update when sports results are updated, news articles are added +- Mercure - https://github.com/symfony/mercure +- LiveTwig - whole block or whole section, and live update `render_live` +- Turbolinks - replace whole body, keeps CSS and JS in memory. Merges new stuff + in. `helthe/turbolinks` +- ReactPHP - shares kernel between requests + +### Writing better code with Twig + +- Keep templates simple. Avoid spaghetti code, only about UI. HTML or small + amounts of Twig. +- Avoid delimeter chains + - Bad:`blog_post.authors.first.user_account.email_address` + - Good `{{ blog_post.authors_email_address }}` + - Less brittle, slow + +* Filters + - Use filters to be precise + - Custom filters + - Avoid chains. Can cause odd results. Create a new filter in PHP +* Functions + - Write your own functions + - Simpler templates + - Get data, can use boolean statements +* Components + - Break a page into components rather than one large page + - `include()` + - Use `only` to only pass that data. less tightenly coupled. + * `render` calls the whole of Symfony, boots Kernel, can be expensive and slow + * Loosely couple templates and controllers + - Keep responses simple + - What makes sense + - if you need extra data in the template, get it in the template + * View models + - Mixed results + - `BlogPostViewModel` + - Can result in boilerplate code + - Can be useful if the view model is different to the Entity + * DRY + - "Don't repeat yourself" + +- Faster development + - Separate UI tests from back-end tests. Different layers for different teams. + People don't need to run everything if they are only changing certain + things. + +* Help your front end + - Webpack - Encore + - Type hinting in functions and filters, easier to debug + - Logging + - Friendly exceptions - help front-end devs by returning meaningful, readbale + errors + - Web Debug Toolbar and Profiler, provide training for toolbar and profilers + - Twig-friendly development environment - Twig support in IDEs and text + editors + +SPAs are sometimes teh right solution. Why do they want to use it, can the same +benefits be added with Twig? + +3 most important points: + +- Profile, identidy, optimise, monitor +- Loosely couple templates to your app code +- Help your front ends - put your front end developers first +- You don't need to use a SPA for single pages, use JavaScript for that one + page. It doesn't need to be all or nothing. + +## BDD Your Symfony Application (Kamil Kokot) + +- Applying BDD to Sylius +- 2 years since release of Sylius (Symfony 2 alpha) +- The business part is more important than the code part + +### What is BDD? + +- Behaviour driven development. Combines TDD and DDD, into an agile methodology +- Encourages communication and creates shared understanding +- Living, executable documentation that non-programmers understand. Always + correct. +- Feature file + - Feature + - Scenario - example of the behaviour for this feature. Simple, atomic. (e.g. + I need a product in order to add it to a cart) + - In order to... + - Who gets the benefit? + +### BDD in practice + +- Feature: booking flight tickets +- Scenario: booking flight ticket for one person + - Given there are the following flights... + - When I visit '/flight/LTN-WAW' + - Then I should be on '/flight/LTN-WAW' + - Add I should see "Your flight has been booked." in "#result" +- In the BDD way - what is the business logic? What is the value for this + scenario? What is the reason 'why', and who benefits from this? + - We just need to know that there are 5 seats left on a flight + - Talk and communicate about how the feature is going to work - not just + developers + - BDD aids communication +- Questions we can ask + - Can we get a different outcome when the context changes? + - When there was only one seat available + - When there were no available seats + - Can we get the same outcome when the event changes? Can we change 'When' and + 'Then stays the same' + - When it is booked for an adult and a child + - When it is booked for an adult + - Does anything else happen that is not mentioned? + - Generate an invoice if a seat is booked + - a pilot would like to get a notification that a seat was booked. + * Figuring out the rules + - Adults are 15+ years old + - Children are 2-14 years old + - Infants and children can only travel with an adult + - We don't allow for overbooking + - Translating rules into examples + - Add a new scenario for each rule - e.g. don't allow over booking + - "And the flight should be no longer available..." + +### Behat + +- Used to automate and execute BDD tests, also SpecDDD +- maps steps to PHP code +- Given a context, when an event, then an outcome +- Domain Context, API context +- class implements `Context`, annotations for `@Given`, `@When`, `@Then`. allows + for arguments and regular expressions +- Suites: change what code is executed, and what scenarios are executed. context + and tags +- FriendsOfBehat SymfonyExtension - integrates Behat with Symfony + - Contexts registered as Symfony services - inject dependencies, service as a + context in Behat. Need to be 'public' for it to work + - Reduces boilerplate code. Supports autowiring. + - Zero configuration + +### Domain context + +- `Given` verb matches `@Given` annotation. Same for `When` and `Then`. +- Transformers, type hint name string, return Client instance + +### API context + +- inject `FlightBookingService` and `KernelBrowser` +- Use `$this->kernelBrowser->request()` +- Use `assert()` function wuthin `@Then` + +### Back to reality - how it's done with Sylius + +- Business part applies to all context. Start talking about what needs to be + done, start communicating +- Implement contexts for UI and API +- 12716 steps, 1175 scenarios, 8 min 8 sec, 2.4 scenarios /sec +- 12x faster than JS (17 min 48 sec, 0.19 scenario / sec) +- Treat test CI environment like production + + - Turn off debug settings, add caching + - Enable OPcache + +- Write features in a natural way +- Too many setup steps - merge steps. less visual debt. e.g. Create currency, + zone and locale when creating a store +- Avoid scenarios that are too detailed. You should specify only what's + important to this scenario. + +## Migrating to Symfony one route at a time (Steve Winter) + +- New client with an old application, built in an old version of another + framework with unusual dependency management, no tests, no version control and + deploying via FTP. Done over a ~3 month period. + +- Subscription based index of suppliers +- New requirements to implement by the client +- Our requirements: Needed a deployment process, make it testable, fix the build + chain +- Solution attempt 1: Migrate to a new version of the current framework + - Minor template and design changes were fine + - Modifiy features, add new dependencies. +- Solution attempt 2: Upgrade to the latest version - same outcome due to + multiple BC breaks (no semver), lots of manual steps +- Solution attempt 3: Symfony! + - Semver! Backwards compatibility promise + - Symfony app to run in parallel, Apache proxy rules and minor changes to the + legacy app, added data transfer mechanisms + - Anything new done in Symfony + - Installed on the same server with it's own vhost but not publicly accessible + - Deployed independently of legacy app + +### Apache proxy rules + +Proxy `/public` to symfony app + +### Legacy app + +- Shared cookie for single login between apps - user account details (name etc), + session details (login time) + +### Added functionality + +- Built in Symfony +- new proxy rules for new routes +- Add menu links to legacy app menu +- How do we show how many reminders are active? + - Symfony based API called from the front-end + +### Migrating routes + +- Rebuilt or extend in Symfony app +- Test and deploy, then update the apache config to add new proxy rules + +### A gotcha + +- Legacy app uses CSRF +- Needed to track the token, added to shared cookie and pass through to the + Symfony side + +### Storing data + +- Both apps using the same data with different credentials +- Some shared tables, some tables are specific to each app + +### Remaining challenges + +- User session management, still handled by legacy app +- Templating/CSS - two versions of everything + - Next step: move all CSS to Symfony + +### Summary + +- Add Symfony app, Apache proxy rules for routes +- User transfer mechanisms +- New functionality added in Symfony + +### Is this right for you? + +It depends. Fine for a 'modest' size. Use a real proxy for larger scale apps, +use different servers with database replication. + +## Closing Keynote: The fabulous World of Emojis and other Unicode symbols (Nicolas Grekas) + +- ASCII. Still used today. Map between the first 128 numbers to characters. OK + for UK and US. +- 256 numbers in Windows-1252 (character sets). Each country had their own set. +- It's legacy. 0.2% for Windows-1252. 88.8% for UTF-8 (Feb 2017) +- Unicode: 130k characters, 135 scripts (alphabets) +- Validation errors using native alphabet - e.g. invalid last name when + submitting a form +- 17 plans, each square is 255 code points +- Emojis are characters, not images +- Gliph is a visual representation of a character +- From code points to bytes + - UTF-8: 1,2,3 or 4 bytes + - UTF16: 2 or 4 bytes + - UTF-32: 4 bytes +- UTF-8 is compatible with ASCII +- Case sensitivity - 1k characters are concerned. One uppercase letter, two + lower case variants. Turkish exception (similar looking letters that are + different letters with different meanings). Full case folding. +- Collations - ordering is depends on the language. 'ch' in Spanish is a single + character. +- Single number in unicode to represent accents. Combining characters. +- Composed (NFC) and decomposed (NFD) forms - normalisation for comparison +- Grapheme clusters - multiple characters, but one letter as you write it + (separate characters for letters and accent) +- Emjois - combining characters. e.g. Combine face with colour. Different codes + and character names. Also applies to ligatures. A way to combine several + images together into one single visual representation. + +### unicode fundamentals + +- uppercase, lowercase, folding +- compositions, ligatures +- comparistions - normalisations and collations +- segmentation: characters, words, sentences and hyphens +- locales: cultural conventions, translitterations +- identifiers & security, confusables +- display: direction, width + +### unicode in practice + +- MySQL - `utf*_*`. `SET NAMES utf8mb4` for security and storing emojis. Cannot + store emojis with `utf8` + +### in php + +- `mb_*()` +- `iconv_*()` +- `preg_*()` +- `grapheme_*()` `normalizer_*()` +- `symfony/polyfill-*` - pure PHP implementation +- Made a component - **symfony/string** - + https://github.com/symfony/symfony/pull/33553 +- Object orientated api for strings. Immutable value objects +- `AbstractString` + - `GraphemeString` + - `Utf8String` + - `BinaryString` + +* AbstractString - Methods to serialize, get length, to binary or grapheme or + utf8 + - Methods for starts with, ends with, is empty, join, prepend, split, trim, + title etc diff --git a/source/_posts/looking-forward-to-drupalcamp-london.md b/source/_posts/looking-forward-to-drupalcamp-london.md new file mode 100644 index 00000000..ca95135b --- /dev/null +++ b/source/_posts/looking-forward-to-drupalcamp-london.md @@ -0,0 +1,66 @@ +--- +title: Looking forward to DrupalCamp London +date: 2018-02-27 +excerpt: This weekend is DrupalCamp London 2018. I’ll be there along with a number of my Microserve colleagues. +tags: + - drupal + - drupalcamp + - drupalcamp-london + - speaking +--- + +This weekend is [DrupalCamp London 2018][1]. I’ll be there along with a number +of my [Microserve][2] colleagues. + +I look forward to DrupalCamp London every year, partly because it was the first +DrupalCamp that I attended back in 2014. It was also the first DrupalCamp that I +[gave a talk][3] at, when I presented a session about Git Flow having given only +one user group talk before. + +I’ve presented sessions at every DrupalCamp London since (including two last +year), and I’m lucky enough to be [speaking again this year][4] due to one of +the originally announced speakers no longer being able to make it to the event. + +Here are some other sessions that I’m hoping to see (in no particular order): + +- Keynote by [Ryan Szrama][5] from [Commerce Guys][6] +- [Drupal 8 Services And Dependency Injection](https://drupalcamp.london/session/drupal-8-services-and-dependency-injection) + by Phil Norton +- [Growing developers with Drupal](https://drupalcamp.london/session/growing-developers-drupal) + by Fran Garcia-Linares (fjgarlin) +- [How to make it easier for newcomers to get involved in Drupal](https://drupalcamp.london/session/how-make-it-easier-newcomers-get-involved-drupal) + by heather +- [Let’s take the best route - Exploring Drupal 8 Routing System](https://drupalcamp.london/session/lets-take-best-route-exploring-drupal-8-routing-system) + by surbhi +- [New recipe of Decoupling: Drupal 8, Symfony and Slim Framework](https://drupalcamp.london/session/new-recipe-decoupling-drupal-8-symfony-and-slim-framework) + by Jyoti Singh +- [Plugin API by examples](https://drupalcamp.london/session/plugin-api-examples) + by Gabriele (gambry) +- [Value of mentorship in the community](https://drupalcamp.london/session/value-mentorship-community) + by Hussain Abbas (hussainweb) +- [Warden - Helping Drupal Agencies Sleep at Night](https://drupalcamp.london/session/warden-helping-drupal-agencies-sleep-night) + by Mike Davis + +Unfortunately there are some time slots where I’d like to see more than one of +the talks (including when I’m going to be speaking). This regularly happens at +conferences, but I’ll look forward to watching those on [YouTube][7] after the +event. + +I’m also looking forward to catching up with former colleagues, spending some +time in the "hallway track" and hopefully doing some sprinting too! + +## Finally + +For nostalgia, [here’s the blog post][0] that I wrote before I attended my first +DrupalCamp London. + +See everyone this weekend! + +[0]: {{site.url}}/blog/2014/02/09/drupalcamp-london-2014 +[1]: https://drupalcamp.london +[2]: {{site.companies.microserve.url}} +[3]: {{site.url}}/talks/git-flow +[4]: {{site.url}}/talks/deploying-drupal-fabric +[5]: http://ryanszrama.com +[6]: https://commerceguys.com +[7]: https://www.youtube.com/channel/UCsaB96zszIP4Y3czs-ndiIA diff --git a/source/_posts/mediacurrent-contrib-half-hour-is-back.md b/source/_posts/mediacurrent-contrib-half-hour-is-back.md new file mode 100644 index 00000000..0402a70f --- /dev/null +++ b/source/_posts/mediacurrent-contrib-half-hour-is-back.md @@ -0,0 +1,67 @@ +--- +title: Yay, the Mediacurrent Contrib Half Hour is Back! +date: 2018-03-02 +excerpt: Mediacurrent’s "contrib half hour sessions" are back. +tags: + - contribution + - drupal + - open-source +has_tweets: true +--- + +Back in November, [Mediacurrent introduced][1] the contrib half hour - a weekly +online meeting to provide guidance and assistance on contributing to Drupal and +Drupal projects. A range of topics were covered in the first few sessions, +including finding and testing bug fixes, Composer, Drush, and how to re-roll +patches. + +From Damien's [introductory blog post][2]: + +> Not sure what this whole "patch" thing is? Have a core change that you can't +> quite finish? Running into a problem with a contrib module, or a theme, or a +> 3rd party library, and not sure how to fix it? New to maintaining a module and +> unsure of what to do next? Wondering how to get your module through the +> security opt-in process? Is your project's issue queue getting you down? Join +> us every Thursday at noon EST for the Mediacurrent Contrib Half Hour where +> we'll be available to help solve contrib challenges. +> +> Each week we'll host a live meeting to give step-by-step guidance on some best +> practices for contributing to Drupal, and provide Q and A assistance for our +> favorite open source (OSS) content management system (CMS). The meetings will +> be lead by yours truly, Damien McKenna, a prolific contributor to the Drupal +> community, and my coworkers here at Mediacurrent. + +There is also an [updates blog post][3] that continues to show the latest +information, and the video recordings are [uploaded to YouTube][0] after the +session. Here is the first one from November: + + + +I enjoyed watching the first few videos, as I’m always interested in +contribution to Drupal and open-source and how to encourage it, but then no new +videos were uploaded for a while and I hoped that it hadn’t faded away. + +I’m glad to see today that it’s back and that all of the previous videos have +been uploaded and added to the [YouTube playlist][0], and that [on the update +post][3] there are scheduled topics for the rest of this month including +documentation and automated testing. + +
+ +
+ +I do enjoy watching these, and I like both the presentation and Q&A format that +they alternate between. I’ll look forward to catching up over the next few days, +and to hopefully seeing them continue to be uploaded after future meetings. + +Thanks Damien and Mediacurrent! + +[0]: https://www.youtube.com/playlist?list=PLu-MxhbnjI9rHroPvZO5LEUhr58Yl0j_F +[1]: + https://www.mediacurrent.com/blog/introducing-mediacurrent-contrib-half-hour +[2]: + https://www.mediacurrent.com/blog/introducing-mediacurrent-contrib-half-hour +[3]: + https://www.mediacurrent.com/blog/updates-mediacurrent-contrib-half-hour-weekly-meeting diff --git a/source/_posts/migrating-drupal-8-introduction.md b/source/_posts/migrating-drupal-8-introduction.md new file mode 100644 index 00000000..cef81271 --- /dev/null +++ b/source/_posts/migrating-drupal-8-introduction.md @@ -0,0 +1,22 @@ +--- +title: 'Migrating to Drupal 8: Introduction' +excerpt: An introduction to the 'Migrating to Drupal 8' blog post series. +date: 2020-08-12 +tags: + - drupal + - drupal-8 + - drupal-planet +--- + +I recently finished porting this website from a static site generator to Drupal 8, meaning that this site has now been powered by three different major versions of Drupal (6, 7 and 8) as well as by two static site generators since it was first launched in early 2010. + +The majority of the content was imported using migrations from JSON feeds that I created. This included: + +- Blog tags +- Blog posts +- Talks +- Redirects + +In some follow-up posts, I'll be looking at each migration separately, describing any issues and look at how it was used to import its respective content. + +I'll update this post with the links to the follow-up posts, and they are also available from the [blog series' page](/taxonomy/term/165). diff --git a/source/_posts/minimum-core-version.md b/source/_posts/minimum-core-version.md new file mode 100644 index 00000000..aaeb69e6 --- /dev/null +++ b/source/_posts/minimum-core-version.md @@ -0,0 +1,96 @@ +--- +title: How to Define a Minimum Drupal Core Version +date: 2015-04-03 +excerpt: How to define a minimum Drupal core version for your module or theme. +tags: + - drupal + - drupal-7 + - drupal-planet +meta: + og: + title: 'How to Define a Minimum Drupal Core Version' + excerpt: 'How to define a minimum Drupal core version for your module or theme.' + type: article +--- + +This week, my first code patch was +[committed to Drupal core](https://www.drupal.org/node/2394517#comment-9773143). +The patch adds the `user_has_role()` function to the user module, to simplify +the way to check whether a user in Drupal has been assigned a specific role. +This is something that I normally write a custom function for each project, but +it's now available in Drupal core as of +[7.36](https://www.drupal.org/drupal-7.36-release-notes). + +But what if someone is using a core version less than 7.36 and tries using the +function? The site would return an error because that function wouldn't exist. + +If you're building a new Drupal site, then I'd assume that you're using a latest +version of core, or you have the opportunity to update it when needed. But what +if you're writing a contrib module? How can you be sure that the correct minimum +version of core? + +## Setting Dependencies + +What I'm going to be doing for my contrib projects is defining a minimum version +of Drupal core that the module is compatible with. If this dependency isn't met, +the module won't be able to be enabled. This is done within your module's .info +file. + +### Adding a Simple Dependency + +You can define a simple dependency for your module by adding a line this this to +your project's .info file: + +```bash +dependencies[] = views +``` + +This would make your module dependant on having the +[Views](https://www.drupal.org/project/views) module present and enabled, which +you'd need if you were including views as part of your module, for example. + +### Adding a Complex Dependency + +In the previous example, our module would enable if _any_ version of Views was +enabled, but we need to specify a specific version. We can do this by including +version numbers within the dependencies field in the following format: + +```bash +dependencies[] = modulename (major.minor) +``` + +This can be a for a specific module release or a branch name: + +```bash +dependencies[] = modulename (1.0) +dependencies[] = modulename (1.x) +``` + +We can also use the following as part of the field for extra granularity: + +- = or == equals (this is the default) +- > greater than +- < lesser than +- > = greater than or equal to +- <= lesser than or equal to +- != not equal to + +In the original scenario, we want to specify that the module can only be enabled +on Drupal core 7.36 or later. To do this, we can use the "greater than or equal +to" option. + +```ini +dependencies[] = system (>=7.36) +``` + +Because we need to check for Drupal's core version, we're using the system +module as the dependency and specifying that it needs to be either equal to or +greater than 7.36. If this dependency is not met, e.g. Drupal 7.35 is being +used, then the module cannot be enabled rather than showing a function not found +error for `user_has_role()` when it is called. + +![A screenshot of the modules page showing System as a dependency for a custom module.](/images/blog/minimum-drupal-version-d7.png) + +## External Links + +- [Writing module .info files (Drupal 7.x)](https://www.drupal.org/node/542202#dependencies) diff --git a/source/_posts/my-first-blog-post-published-for-inviqa.md b/source/_posts/my-first-blog-post-published-for-inviqa.md new file mode 100644 index 00000000..f1aca7ab --- /dev/null +++ b/source/_posts/my-first-blog-post-published-for-inviqa.md @@ -0,0 +1,12 @@ +--- +title: My first blog post published for Inviqa +excerpt: My first blog post has been published on the inviqa.com website. +date: 2020-04-29 +tags: + - drupal + - testing +--- + +My first blog post was published on the Inviqa website last week. Is an introduction to automated testing in Drupal, which also includes a recap of the workshop that I recently gave at DrupalCamp London. + +The blog post can be found at , and there's more information about the workshop specifically at . diff --git a/source/_posts/my-first-six-months-transport-wales.md b/source/_posts/my-first-six-months-transport-wales.md new file mode 100644 index 00000000..6f08b3c5 --- /dev/null +++ b/source/_posts/my-first-six-months-transport-wales.md @@ -0,0 +1,45 @@ +--- +title: "My first six months at Transport for Wales" +excerpt: + It's been a busy six months since I started working as a Lead Software + Developer at Transport for Wales. +date: 2021-12-03 +tags: ["personal"] +--- + +It's been a busy six months since I started working as a Lead Software +Developer at Transport for Wales back in June. + +My main focus has been being part on the development team for the new +[tfw.wales] and [trc.cymru] websites, which replaced the previous tfwrail.wales +and trctrenau.cymru websites. + +Some of my personal highlights have been: + +- Completion of the initial phase 1 project that went live in September, based + on Drupal 8.9. +- Upgrading the phase 1 project from Drupal 8.9 to 9.2 over several iterations + alongside new development and other BAU tasks. +- Creating containerised versions of each of our applications using Docker, + creating consistent local environments for us to use. +- The introduction of automated testing and other code quality tools, such as + PHPStan for static analysis, for any new code, and automating this using + Bitbucket Pipelines and the new Docker images. +- Continuing to work with a range of technologies - Drupal, Symfony and API + Platform, Vue.js, TypeScript, Acquia Cloud, and Amazon AWS and S3. + +We've already been working on the second phase of the TfW websites, integrating +some of our other websites, and adding new features whilst continuing to +maintain and improve the existing codebase. + +I'm currently supporting another project team at the moment too - their project +is going live next week - and will look into writing more week- or month-notes +going forward. + +I've continued [working with Neovim](/blog/going-full-vim) as my daily +IDE/text-editor tool, have continued working on my [freelance development and +consulting projects](/drupal-php-developer), and started to squeeze in [some +more live streams](https://oliverdavies.live) too! + +[tfw.wales]: https://tfw.wales +[trc.cymru]: https://trc.cymru diff --git a/source/_posts/my-new-drupal-modules.md b/source/_posts/my-new-drupal-modules.md new file mode 100644 index 00000000..3c2cb4c5 --- /dev/null +++ b/source/_posts/my-new-drupal-modules.md @@ -0,0 +1,24 @@ +--- +title: My new Drupal modules +date: 2012-07-12 +excerpt: After a busy few days, I've released two new contrib Drupal modules. +tags: + - accessibility + - drupal + - drupal-6 + - drupal-7 + - drupal-modules + - drupal-planet +--- + +After a busy few days, I've released two new contrib Drupal modules. + +- [Block Aria Landmark Roles](http://drupal.org/project/block_aria_landmark_roles) - + Inspired by [Block Class](http://drupal.org/project/block_class), this module + adds additional elements to the block configuration forms that allow users to + assign a ARIA landmark role to a block. +- [Nomensa Accessible Media Player](http://drupal.org/project/nomensa_amp) - + Provides integration with Nomensa's + [Accessible Media Player](https://github.com/nomensa/Accessible-Media-Player). + +Documentation for both to follow shortly on Drupal.org. diff --git a/source/_posts/my-sublime-text-2-settings.md b/source/_posts/my-sublime-text-2-settings.md new file mode 100644 index 00000000..375ace33 --- /dev/null +++ b/source/_posts/my-sublime-text-2-settings.md @@ -0,0 +1,106 @@ +--- +title: My Sublime Text 2 settings +date: 2012-10-25 +excerpt: Sublime Text 2 has been my text editor of choice for the past few months, and I use it at home, in work, and on any virtual machines that I run. So rather than having to manually re-enter my settings each time, I thought that I'd document them here for future reference. +tags: + - sublime-text +--- + +[Sublime Text 2](http://www.sublimetext.com/2) has been my text editor of choice +for the past few months, and I use it at home, in work, and on any virtual +machines that I run. So rather than having to manually re-enter my settings each +time, I thought that I'd document them here for future reference. + +These preferences ensure that the code is compliant with +[Drupal coding standards](http://drupal.org/coding-standards 'Drupal coding standards on Drupal.org') - +using two spaces instead of a tab, no trailing whitespace, blank line at the end +of a file etc. + +## Preferences + +These can be changed by going to Preferences > Settings - User. + +```json +{ + "color_scheme": "Packages/Theme - Aqua/Color Schemes/Tomorrow Night Aqua.tmTheme", + "default_line_ending": "unix", + "ensure_newline_at_eof_on_save": true, + "fallback_encoding": "UTF-8", + "file_exclude_patterns": + [ + "*.pyc", + "*.pyo", + "*.exe", + "*.dll", + "*.obj", + "*.o", + "*.a", + "*.lib", + "*.so", + "*.dylib", + "*.ncb", + "*.sdf", + "*.suo", + "*.pdb", + "*.idb", + ".DS_Store", + "*.class", + "*.psd", + "*.db", + "*.sublime*" + ], + "folder_exclude_patterns": + [ + ".svn", + ".git", + ".hg", + "CVS", + "FirePHPCore" + ], + "font_options": + [ + "no_bold", + "no_italic" + ], + "font_size": 16.0, + "highlight_line": true, + "ignored_packages": + [ + ], + "line_padding_bottom": 1, + "rulers": + [ + 80 + ], + "save_on_focus_lost": true, + "shift_tab_unindent": true, + "tab_size": 2, + "theme": "Soda Light.sublime-theme", + "translate_tabs_to_spaces": true, + "trim_automatic_white_space": true, + "trim_trailing_white_space_on_save": true, + "word_wrap": false +} +``` + +## Key bindings + +These can be changed by going to Preferences > Key Bindings - User. + +```json +[ + { "keys": ["alt+s"], "command": "toggle_side_bar" }, + { "keys": ["alt+r"], "command": "reindent" } +] +``` + +## Packages + +These are the packages that I currently have installed. + +- [DocBlockr](https://github.com/spadgos/sublime-jsdocs 'DocBlockr on GitHub') +- [Drupal API](https://github.com/BrianGilbert/Sublime-Text-2-Goto-Drupal-API) +- [LESS](https://github.com/danro/LESS-sublime) +- [Package Control](http://wbond.net/sublime_packages/package_control) +- [Sublime CodeIntel](http://github.com/Kronuz/SublimeCodeIntel) +- [Theme - Soda](https://github.com/buymeasoda/soda-theme) diff --git a/source/_posts/neovim-database-plugin-vim-dadbod-ui.md b/source/_posts/neovim-database-plugin-vim-dadbod-ui.md new file mode 100644 index 00000000..ab2e5078 --- /dev/null +++ b/source/_posts/neovim-database-plugin-vim-dadbod-ui.md @@ -0,0 +1,5 @@ +--- +title: test +draft: true +date: ~ +--- diff --git a/source/_posts/nginx-redirects-query-string-arguments.md b/source/_posts/nginx-redirects-query-string-arguments.md new file mode 100644 index 00000000..cc7be79b --- /dev/null +++ b/source/_posts/nginx-redirects-query-string-arguments.md @@ -0,0 +1,57 @@ +--- +title: Nginx Redirects With Query String Arguments +date: 2017-01-31 +excerpt: How to redirect from an old domain to a new one, and also to redirect from the root example.com domain to the canonical www subdomain. +tags: + - nginx +--- + +This is an example of how my Nginx configuration looked to redirect from an old +domain to a new one, and also to redirect from the root `example.com` domain to +the canonical `www` subdomain. + +```nginx +server { + listen 80; + + server_name example.com; + server_name my-old-domain.com; + server_name www.my-old-domain.com; + + return 301 https://www.example.com$uri; +} +``` + +It also redirects the URI value, e.g. from `http://example.com/test` to +`http://example.com/test`, but I noticed recently though that any the query +string would be lost - e.g. `http://example.com/?test` would redirect to +`http://www.example.com` and the `?test` would be dropped. The application that +I built references images based on the query string, so I wanted these to be +included within the redirect. + +This was fixed by making a small change to my `return` statement. + +Before: + +```nginx +return 301 https://www.example.com$uri; +``` + +After: + +```nginx +return 301 https://www.example.com$uri$is_args$args; +``` + +`$is_args` is an empty string if there are no arguments, or a `?` to signify the +start of the query string. `$args` then adds the arguments (`$query_string` +could also be used with the same result). + +Here is an demo of it working on this website: + +![](/images/blog/nginx-redirect-with-args.gif) + +## Resources + +- [Query string](https://en.wikipedia.org/wiki/Query_string) +- [Nginx ngx_http_core_module](http://nginx.org/en/docs/http/ngx_http_core_module.html) diff --git a/source/_posts/null-users-system-users-drupal.md b/source/_posts/null-users-system-users-drupal.md new file mode 100644 index 00000000..b63109cf --- /dev/null +++ b/source/_posts/null-users-system-users-drupal.md @@ -0,0 +1,155 @@ +--- +title: Null Users and System Users in Drupal +date: 2018-08-16 +excerpt: Announcing the Null User and System User modules. +tags: + - drupal + - drupal-7 + - drupal-8 + - drupal-modules + - drupal-planet + - php +--- + +Have you ever needed to have a 'special user' to perform tasks on your Drupal +site, such as performing actions based on an API request, or for sending an +internal site message? + +If you just create a new user, how do you identify that user going forward? Do +you hard-code the 'magic' user ID in your custom code? What if the user has a +different ID on different environments of your site? You could declare it in +each environment’s settings file and retrieve it from there, but what then if +you need to do the same on another site? That would mean some duplication of +code - and something that could have been abstracted and re-used. + +I had to do this recently, and rather than just duplicate the code I decided to +make it into it’s own module - which then became two modules. + +## System users + +The [System User module][1] provides a re-usable, generic way to denote users as +'system users', which is not specific to a certain site or environment as this +is value is stored against each individual user in the database. + +'System user' is a term used in Linux, which I thought also applies well to this +scenario. + +From : + +> A system account is a user account that is created by an operating system +> during installation and that is used for operating system defined purposes. +> System accounts often have predefiend user ids. Examples of system accounts +> include the root account in Linux. + +A system user isn’t an account that we’d expect a person to log in with and +perform routine tasks like updating content, but rather for the system (site) to +use to perform tasks like the earlier examples. + +### Declaring a user as a system user + +System User module adds a base field to Drupal’s User entity, which determines +whether or not each user is a system user - i.e. if this field is `TRUE`, that +user is a system user. This means that users can easily be queried to identify +which are system users, without having to rely on magic, environment and site +specific user IDs. This also means that we can have multiple system users, if +needed. + +![](/images/blog/null-users-system-users/drupal-8-users-field-data-table.png){.border +.p-1} + +In the Drupal 8 version of the module, a `SystemUser` is a custom entity, that +contains it’s own `create` method for creating new system users. This is a +essentially a wrapper around `User::create()` that automatically sets the value +of the system user field as part of the creation. + +The original intention is that system users would always be created manually in +an custom install or update hook, however since releasing the module, I’ve also +added an install hook to the module to automatically create a new system user +when the module is installed, basing the username on the site name. + +There is also an open issue to add a Drush command to create a new system user, +and I’d imagine I’ll also add a Drupal Console command too. + +### Retrieving system users + +Whilst you could easily write your own query that retrieves users based on the +value of the system user field, but the module contains a `SystemUserManager` +service that contains methods to do so. It also provides a static helper class +that determines if a specified user is a system user by checking the value of +the system user field. + +``` +// Retrieve the first system user. +$system_user = $this->systemUserManager->getFirst(); + +// Is the specified user a system user? +$is_system_user = SystemUserManager::isSystemUser($user); +``` + +But what do we return if there are no system users? You could return `NULL` or +`FALSE`, but I decided to take a different approach, which became the second +module. + +## Null users + +The [Null User module][2] is an implementation of the [null object pattern][3] +for users in Drupal 8. In this case, a [NullUser][4] is an extension of Drupal’s +`AnonymousUserSession`, which means that it inherits sensible defaults to return +for a non-existent User. Though, through inheritance, the `id`, `getRoles` and +`hasPermission` methods are overridden to return relevant values. + +```php +use Drupal\Core\Session\AnonymousUserSession; + +class NullUser extends AnonymousUserSession { + ... +} +``` + +Null User module is a dependency of System User in Drupal 8, so When no system +user is found from the `getFirst()` method, a `NullUser` is returned. Whilst I +could alternatively have returned `NULL` or `FALSE`, we then would need to check +if the returned value was an object or not before calling methods on it. + +```php +$system_user = $this->systemUserManager->getFirst(); // Returns NULL or FALSE. + +// Need to check if a user was returned or not. +if (!$system_user) { + return; +} + +if ($system_user->isActive()) { + ... +} +``` + +Because instead we’re returning a `NullUser`, which through class inheritance +has the same methods and properties as a regular user, there is no need to do +the additional check as you will always receive a relevant object, and the +expected methods will always be present. + +```php +$system_user = $this->systemUserManager->getFirst(); // Returns a NullUser. + +if ($system_user->isActive()) { + ... +} +``` + +This means we have less code, which also is simpler and more readable. + +System User module is the only one that I’m aware of that makes use of Null +User, but I’ve added a list to the [project page][2] so let me know if you can +think of any others. + +## Resources + +- [Null object pattern][3] +- [Null User module][2] +- [System User module][1] + +[1]: https://www.drupal.org/project/system_user +[2]: https://www.drupal.org/project/null_user +[3]: https://en.wikipedia.org/wiki/Null_object_pattern +[4]: http://cgit.drupalcode.org/null_user/tree/src/NullUser.php?h=8.x-1.x diff --git a/source/_posts/open-sublime-text-2-mac-os-x-command-line.md b/source/_posts/open-sublime-text-2-mac-os-x-command-line.md new file mode 100644 index 00000000..596589c0 --- /dev/null +++ b/source/_posts/open-sublime-text-2-mac-os-x-command-line.md @@ -0,0 +1,23 @@ +--- +title: Open Sublime Text 2 from the Mac OS X Command Line +date: 2012-11-17 +excerpt: How to open Sublime Text from the command line. +tags: + - mac-os-x + - sublime-text + - terminal +--- + +How to open Sublime Text from the command line. + +Paste the following code into the Mac OS X Terminal, assuming that you've +installed Sublime Text 2 into the /Applications folder. + +```bash +$ ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" ~/bin/sublime +``` + +Now you can type `sublime ` open a file or directory in Sublime Text, +or `sublime .` to open the current directory. + +You can also type `sublime --help` to see a list of the available commands. diff --git a/source/_posts/presenting-on-tailwind-css-and-ansible-at-cms-philly.md b/source/_posts/presenting-on-tailwind-css-and-ansible-at-cms-philly.md new file mode 100644 index 00000000..e669aa45 --- /dev/null +++ b/source/_posts/presenting-on-tailwind-css-and-ansible-at-cms-philly.md @@ -0,0 +1,23 @@ +--- +title: Presenting on Tailwind CSS and Ansible at CMS Philly +excerpt: I'll be presenting on Tailwind CSS and deployments with Ansible at CMS Philly on May 1st. +date: 2020-04-24 +tags: + - ansible + - ansistrano + - conference + - drupal + - drupal-planet + - speaking + - tailwind-css +--- + +![](/images/blog/presenting-on-tailwind-css-and-ansible-at-cms-philly/cms-philly-logo.png){.mx-auto} + +I'm happy to be presenting two talks remotely at this year's [CMS Philly](https://cmsphilly.org) conference (formerly [Drupaldelphia](https://www.drupaldelphia.org)). + +The first talk is [Deploying PHP applications with Ansible, Ansible Vault and Ansistrano](/talks/deploying-php-ansible-ansistrano) at 1pm (6pm UK time) where I'll be doing an introduction to Ansible and show how to use Ansistrano to do deploy a Drupal 8 application. + +The second talk is [Taking Flight with Tailwind CSS](/talks/taking-flight-with-tailwind-css) at 2pm (7pm UK time) where I'll show how to configure and use Tailwind CSS. + +CMS Philly is happening virtually on Friday, May 1st via GoToWebinar. diff --git a/source/_posts/presenting-pdf-slides-using-pdfpc-pdf-presenter-console.md b/source/_posts/presenting-pdf-slides-using-pdfpc-pdf-presenter-console.md new file mode 100644 index 00000000..2275139b --- /dev/null +++ b/source/_posts/presenting-pdf-slides-using-pdfpc-pdf-presenter-console.md @@ -0,0 +1,91 @@ +--- +title: Presenting from PDF slides using pdfpc (PDF Presenter Console) +excerpt: My notes from using pdfpc (PDF Presenter Console). +tags: + - speaking +date: 2021-04-23 +--- + +I recently started using PDF files for presentation slides and gave [a talk about a tool called rst2pdf](/talks/building-presenting-slide-decks-rst2pdf) that I use to write slides in reStructuredText and convert them to PDF. This blog post is about another tool that I use to present from the PDF file, which is called the [PDF Presenter Console](https://pdfpc.github.io "The pdfpc website") (or `pdfpc`). + +This is the basic version that you get by running `pdfpc slides.pdf`: + +
+
+ +
+
Image
+
The basic pdfpc speaker view. + +
+
+ +
+ +It opens a speaker notes window that shows the current and next slide, the total number of slides in the presentation, the current slide number, and an increasing amount of time since you started the presentation. + +Here are some tips that I usually use with `pdfpc`. + +## Setting a duration + +If you don't want a timer that shows the amount of time that you've been presenting so far then you can set a duration for the presentation using `pdfpc --duration 10`, and the timer will count down instead. + +
+
+ +
+
Image
+
Showing the presenter notes with a duration to the end of the presentation. + +
+
+ +
+ +This is great if your presentation is has a strict end time such as during a conference schedule. + +## Setting a start time + +As well as a duration, you can add the start time for the presentation by running `pdfpc --start-time=13:00`. This will show you a timer that will count down until the specified start time when you need to start presenting. + +
+
+ +
+
Image
+
Showing the presenter notes with countdown to the start time. + +
+
+ +
+ +Again, this is great if your presentation is has a strict start time such as during a conference. + +## Swapping screens + +When using both my laptop screen and external monitor for presenting (one for the slides, and the other for the speaker notes) it seems that the windows usually open on the opposite screens to the ones that I want. + +I can override this though using the `--switch-screens` option and swap the presentation/presenter screens. + +There are also `--presenter-screen` and `--presentation-screen` options to set the monitor to use for each but I usually find that just swapping them works for me. + +## Presentation overview + +When presenting, you can press the `Tab` key to see an overview of the presentation, with each slide and its number, and where you can easily navigate between slides which is very helpful if, during the Q&A section of the presentation, someone would like to ask a question about or reference a particular slide. + +
+
+ +
+
Image
+
The presentation overview screen + +
+
+ +
+ +## And more... + +There are a lot more options in `pdfpc`. To see more, run `pdfpc --help` or press `?` within the presenter view to see the help page (or `pdfpc --list-bindings`). diff --git a/source/_posts/prevent-apache-displaying-text-files-within-web-browser.md b/source/_posts/prevent-apache-displaying-text-files-within-web-browser.md new file mode 100644 index 00000000..5427894b --- /dev/null +++ b/source/_posts/prevent-apache-displaying-text-files-within-web-browser.md @@ -0,0 +1,28 @@ +--- +title: Prevent Apache from displaying text files within a web browser +date: 2012-05-23 +excerpt: How to prevent Apache from displaying the contents of files like CHANGELOG.txt. +tags: + - apache + - code + - drupal +--- + +When you download [Drupal](http://drupal.org/project/drupal), there are several +text files that are placed in the root of your installation. You don't want or +need these to be visible to anyone attempting to view them in a browser - +especially CHANGELOG.txt as that includes the exact version of Drupal you are +running and could therefore have security implications. + +Rather than delete these files or change the file permissions manually for each +file, I can add the following lines into my VirtualHost configuration. + +``` + + Order deny,allow + Deny from all + +``` + +This prevents any files with a .txt extension from being accessed and rendered +in a web browser. diff --git a/source/_posts/proctor-stevenson.md b/source/_posts/proctor-stevenson.md new file mode 100644 index 00000000..eeed687e --- /dev/null +++ b/source/_posts/proctor-stevenson.md @@ -0,0 +1,20 @@ +--- +title: Proctor & Stevenson +date: 2011-03-31 +excerpt: I’m moving jobs. +tags: + - personal +--- + +2 weeks ago, I handed in my notice of resignation to +[Horse & Country TV](http://horseandcountry.tv)because I've been offered a new +role at [Proctor & Stevenson](http://proctors.co.uk) - a Marketing Design and +Communications agency in Bristol. + +Proctors have an [extensive client list](http://www.proctors.co.uk/clients) - +including [BMW](http://www.proctors.co.uk/clients/bmw-financial-services), +[Panasonic](http://www.proctors.co.uk/clients/panasonic), the +[Open University](http://www.proctors.co.uk/clients/open-university) and +[VOSA](http://www.proctors.co.uk/clients/vosa), and it's going to be a fantastic +opportunity for me to continue expanding my skillset whilst gaining vital +experience. diff --git a/source/_posts/proctors-hosting-next-drupal-meetup.md b/source/_posts/proctors-hosting-next-drupal-meetup.md new file mode 100644 index 00000000..d9dfc034 --- /dev/null +++ b/source/_posts/proctors-hosting-next-drupal-meetup.md @@ -0,0 +1,15 @@ +--- +title: Proctors Hosting the next Drupal Meetup +date: 2011-05-20 +excerpt: Proctor & Stevenson are going to be hosting the next Bristol & South West Drupal meetup. +tags: + - drupal-bristol + - meetups +--- + +My employer, [Proctor & Stevenson](http://www.proctors.co.uk), are going to be +hosting the next Bristol & South West Drupal meetup on the 25th May at our +offices. + +You can [view more details](http://groups.drupal.org/node/147324), or register +[on our website](http://www.proctors.co.uk/Drupal-SWUG-Meetup). diff --git a/source/_posts/psr4-autoloading-test-cases-drupal-7.md b/source/_posts/psr4-autoloading-test-cases-drupal-7.md new file mode 100644 index 00000000..c106daf0 --- /dev/null +++ b/source/_posts/psr4-autoloading-test-cases-drupal-7.md @@ -0,0 +1,143 @@ +--- +title: Using PSR-4 Autoloading for your Drupal 7 Test Cases +excerpt: How to use the PSR-4 autoloading standard for Drupal 7 Simpletest test cases. +tags: + - drupal + - drupal-planet + - drupal-7 + - testing + - simpletest + - php + - psr +date: 2020-02-04 +--- + +

{{ page.excerpt }}

+ +## The Traditional Way + +The typical way of including test cases in Drupal 7 is to add one or more +classes within a `.test` file - e.g. `opdavies.test`. This would typically +include all of the different test cases for that module, and would be placed in +the root of the module’s directory alongside the `.info` and `.module` files. + +In order to load the files, each file would need to be declared within the +`.info` file for the module. + +There is a convention that if you have multiple tests for your project, these +can be split into different files and grouped within a `tests` directory. + +```ini +; Load a test file at the root of the module +files[] = opdavies.test + +; Load a test file from within a subdirectory +files[] = tests/foo.test +files[] = tests/bar.test +``` + +## Using the xautoload Module + +Whilst splitting tests into separate files makes things more organised, each +file needs to be loaded separately. This can be made simpler by using the +[Xautoload module][], which supports wildcards when declaring files. + +[xautoload module]: https://www.drupal.org/project/xautoload + +```ini +files[] = tests/**/*.test +``` + +This would load all of the `.test` files within the tests directory. + +## Using PSR-4 Autoloading + +Another option is to use PSR-4 (or PSR-0) autoloading. + +This should be a lot more familiar to those who have worked with Drupal 8, +Symfony etc, and means that each test case is in its own file which is cleaner, +files have the `.php` extension which is more standard, and the name of the file +matches the name of the test class for consistency. + +To do this, create a `src/Tests` (PSR-4) or `lib/Drupal/{module_name}/Tests` +(PSR-0) directory within your module, and then add or move your test cases +there. Add the appropriate namespace for your module, and ensure that +`DrupalWebTestCase` or `DrupalUnitTestCase` is also namespaced. + +```php +// src/Tests/Functional/OliverDaviesTest.php + +namespace Drupal\opdavies\Tests\Functional; + +class OliverDaviesTest extends \DrupalWebTestCase { + // ... +} +``` + +This also supports subdirectories, so you can group classes within `Functional` +and `Unit` directories if you like. + +If you want to see an real-world example, see the Drupal 7 branch of the +[Override Node Options module][override_node_options]. + +[override_node_options]: + https://git.drupalcode.org/project/override_node_options/tree/7.x-1.x + +### Digging into the simpletest_test_get_all function + +This is the code within `simpletest.module` that makes this work: + +```php +// simpletest_test_get_all() + +// ... + +$module_dir = DRUPAL_ROOT . '/' . dirname($filename); + +// Search both the 'lib/Drupal/mymodule' directory (for PSR-0 classes) +// and the 'src' directory (for PSR-4 classes). +foreach (array( + 'lib/Drupal/' . $name, + 'src', +) as $subdir) { + + // Build directory in which the test files would reside. + $tests_dir = $module_dir . '/' . $subdir . '/Tests'; + + // Scan it for test files if it exists. + if (is_dir($tests_dir)) { + $files = file_scan_directory($tests_dir, '/.*\\.php/'); + if (!empty($files)) { + foreach ($files as $file) { + + // Convert the file name into the namespaced class name. + $replacements = array( + '/' => '\\', + $module_dir . '/' => '', + 'lib/' => '', + 'src/' => 'Drupal\\' . $name . '\\', + '.php' => '', + ); + $classes[] = strtr($file->uri, $replacements); + } + } + } +} +``` + +It looks for a the tests directory (`src/Tests` or +`lib/Drupal/{module_name}/Tests`) within the module, and then finds any `.php` +files within it. It then converts the file name into the fully qualified +(namespaced) class name and loads it automatically. + +### Running the Tests + +You can still run the tests from within the Simpletest UI, or from the command +line using `run-tests.sh`. + +If you want to run a specific test case using the `--class` option, you will now +need to include the fully qualified name. + +``` +php scripts/run-tests.sh --class Drupal\\opdavies\\Tests\\Functional\\OliverDaviesTest +``` diff --git a/source/_posts/published-my-first-docker-images-docker-hub-adr-tools-sculpin-rst2pdf.md b/source/_posts/published-my-first-docker-images-docker-hub-adr-tools-sculpin-rst2pdf.md new file mode 100644 index 00000000..bf2bba18 --- /dev/null +++ b/source/_posts/published-my-first-docker-images-docker-hub-adr-tools-sculpin-rst2pdf.md @@ -0,0 +1,97 @@ +--- +title: Published my first Docker images on Docker Hub (ADR Tools, Sculpin, rst2pdf) +excerpt: I recently released my first images to the Docker Hub, for ADR Tools, the Sculpin site generator, and rst2pdf. +date: 2021-04-20 +tags: + - docker + - rst2pdf + - sculpin +--- + +I've used Docker for some time for local development, making use of container images from Docker Hub and creating my own project-specific images, but I hadn't pushed any to [my Docker Hub profile](https://hub.docker.com/u/opdavies) for anyone else to use - until now. + +I've pushed several images to Docker Hub recently: + +- One for using [ADR Tools](https://github.com/npryce/adr-tools) to work with architectural decision records. +- Two for generating and serving sites built with the [Sculpin static site generator](https://sculpin.io). +- One for working with [rst2pdf](https://rst2pdf.org) that I use for presentation slides, with another image coming for watching and automatically re-compiling the PDF. + +
+
+ +
+
Image
+
My Docker images on Docker Hub + +
+
+ +
+ +## ADR Tools + +- GitHub: https://github.com/opdavies/docker-image-adr-tools +- Docker Hub: https://hub.docker.com/r/opdavies/adr-tools + +The ADR Tools image a simple one that allows me to initialise and configure ADR Tools itself as well as creating new ADR documents without needing to install `adr-tools` locally. + +For example: + +``` +# Initialise the ADR directory +docker run --rm -v $(pwd):/adr opdavies/adr-tools init + +# List the current ADRs. +docker run --rm -v $(pwd):/adr opdavies/adr-tools list + +# Create a new ADR. +docker run --rm -v $(pwd):/adr opdavies/adr-tools new 'A new ADR' +``` + +## Sculpin + +- GitHub: https://github.com/opdavies/docker-image-sculpin-serve +- Docker Hub: https://hub.docker.com/r/opdavies/sculpin, https://hub.docker.com/r/opdavies/sculpin-serve + +The Sculpin image repository contains two images - one for running Sculpin commands such as `sculpin content:create page` to create a new page, and one for generating and serving the Sculpin site that uses the `sculpin generate` command to generate and serve the site as well as watching for changes. + +``` +# Run a "sculpin" CLI command and "composer install" if needed. +docker run --rm -v $(pwd):/app opdavies/sculpin + +# Generate and serve the Sculpin site. +docker run --rm -p 8000:8000 -v $(pwd):/app opdavies/sculpin-serve +``` + +I've tested this with some of my own personal and client Sculpin projects, as well as the official [Sculpin Blog skeleton](https://github.com/sculpin/sculpin-blog-skeleton). + +
+
+ +
+
Image
+
The Sculpin Blog Skeleton running with the sculpin-serve image + +
+
+ +
+ +## rst2pdf + +- GitHub: https://github.com/opdavies/docker-image-rst2pdf +- Docker Hub: https://hub.docker.com/r/opdavies/rst2pdf + +rst2pdf is a tool that I use primarily for presentation slide decks (I [gave a talk about this](/talks/building-presenting-slide-decks-rst2pdf) at one of the PHP South Wales meetups). + +The rst2pdf image installs Python and rst2pdf so that I can easily generate the PDF files from reStructuredText input files, including any extra arguments that are required. + +``` +# A simple example. +docker run --rm -it -v $(pwd):/rst2pdf rst2pdf input.rst + +# An example including some additional arguments. +docker run --rm -it -v $(pwd):/rst2pdf rst2pdf slides.rst -b2 -s main -e preprocess +``` + +I'm currently adding an `rst2pdf-watch` image too, similar to `sculpin-watch` that will watch the files using `nodemon` and automatically regenerate the PDF files when files change. I'm not entirely sure of the syntax for this yet but I'll push it to Docker Hub too once I've figured it out and have it working. diff --git a/source/_posts/published-my-first-npm-package.md b/source/_posts/published-my-first-npm-package.md new file mode 100644 index 00000000..2937b23e --- /dev/null +++ b/source/_posts/published-my-first-npm-package.md @@ -0,0 +1,117 @@ +--- +title: Published my first NPM package +date: 2018-12-16 +excerpt: Yesterday I published my first module onto NPM, and it’s a plugin for Tailwind CSS to be used alongside Vue.js. +tags: + - npm + - tailwind-css + - vuejs +--- + +Yesterday I published my first module onto NPM, and it’s a plugin for [Tailwind +CSS][tailwind] to be used alongside [Vue.js](https://vuejs.org). + +The plugin adds classes for showing and hiding elements in different display +variations in combination with Vue's +[v-cloak directive](https://vuejs.org/v2/api/#v-cloak), which I originally saw +in [the first 'Building Kitetail' video](https://youtu.be/XUXpcbYQ_iQ?t=2360). +These are useful for when you want an element to be visible whilst Vue is +compiling, and hidden afterwards. + +Here is the compiled CSS that is added by the plugin: + +```css +[v-cloak] .v-cloak-block { + display: block; +} + +[v-cloak] .v-cloak-flex { + display: flex; +} + +[v-cloak] .v-cloak-hidden { + display: none; +} + +[v-cloak] .v-cloak-inline { + display: inline; +} + +[v-cloak] .v-cloak-inline-block { + display: inline-block; +} + +[v-cloak] .v-cloak-inline-flex { + display: inline-flex; +} + +[v-cloak] .v-cloak-invisible { + visibility: hidden; +} + +.v-cloak-block, +.v-cloak-flex, +.v-cloak-inline, +.v-cloak-inline-block, +.v-cloak-inline-flex { + display: none; +} +``` + +The `v-cloak` directive exists on an element until Vue finishes compiling, after +which it is removed. Therefore adding a `v-cloak-block` class to an element will +make it `display: block` whilst Vue is compiling and the element is cloaked, and +`display: none` afterwards when the Vue markup is compiled and rendered. + +In my `base.html.twig` template, I’ve added `v-cloak` to the wrapper div within +the `body`. + +
+ +```twig + +
+ {# ... #} +
+ +``` + +
+ +Within my `navbar.html.twig` partial, I have a placeholder div that also +contains the site name, which is instantly visible but has the `v-cloak-block` +class so it’s hidden once Vue has compiled and the `Navbar` Vue component is +visible instead. + +
+ +```twig +
+
+
+ {{ site.title }} +
+ + +
+
+``` + +
+ +I was originally surprised that these classes weren’t included as part of +Tailwind or as part of an existing plugin, but as I’ve already used these styles +on several projects that include Vue.js with Symfony or Sculpin, it made sense +to extract it into a plugin and make it available as a npm package which I can +easily add to any project - as well as making it easier to maintain if I need to +add additional variations at a later point. + +**You can view [the package on npmjs.com][npm], and [the code repository on +GitHub][github].** + +[github]: https://github.com/opdavies/tailwindcss-vuejs +[npm]: https://www.npmjs.com/package/tailwindcss-vuejs +[tailwind]: https://tailwindcss.com diff --git a/source/_posts/publishing-sculpin-sites-with-github-pages.md b/source/_posts/publishing-sculpin-sites-with-github-pages.md new file mode 100644 index 00000000..25ccce3a --- /dev/null +++ b/source/_posts/publishing-sculpin-sites-with-github-pages.md @@ -0,0 +1,113 @@ +--- +title: Publishing Sculpin Sites with GitHub Pages +date: 2017-07-13 +excerpt: How I moved my website to GitHub pages. +tags: + - github + - php + - sculpin +meta: + image: + url: '/images/blog/jackson-octocat.png' + type: 'image/png' + height: 200 + width: 451 +--- + +

![](/images/blog/jackson-octocat.png)

+ +Earlier this week I moved this site from my personal Linode server to [GitHub +Pages][0]. + +This made sense as I already kept the source code in [on GitHub][1], the issue +was that GitHub Pages doesn’t know how to dynamically parse and generate a +Sculpin site like it does with some other static site generators. It can though +parse and serve HTML files, which is what Sculpin generates. It’s just a case of +how those files are added to GitHub. + +I’ve seen different implementations of this, mostly where the Sculpin code is on +one branch, and the generated HTML code is on a separate `gh-pages` or `master` +branch (depending on your repository name). I’m not fond of this approach as it +means automatically checking out and merging branches which can get messy, and +also it’s weird to look at a repo’s branches page and see one branch maybe tens +or hundreds of commits both ahead and behind the default branch. + +This has been made simpler and tidier now that we can use a `docs` directory +within the repository to serve content. + + + +This means that I can simply re-generate the site after making changes and add +it as an additional commit to my main branch with no need to switch branches or +perform a merge. + +To simplify this, I’ve added a new [publish.sh script][3] into my repository to +automate the sites. This is how it currently looks: + +```bash +#!/usr/bin/env bash + +SITE_ENV="prod" + +# Remove the existing docs directory, build the site and create the new +# docs directory. +rm -rf ./docs +vendor/bin/sculpin generate --no-interaction --clean --env=${SITE_ENV} +touch output_${SITE_ENV}/.nojekyll +mv output_${SITE_ENV} docs + +# Ensure the correct Git variables are used. +git config --local user.name 'Oliver Davies' +git config --local user.email oliver@oliverdavies.uk + +# Add, commit and push the changes. +git add --all docs +git commit -m 'Build.' +git push origin HEAD +``` + +This begins by removing the deleting the existing `docs` directory and +re-generating the site with the specified environment. Then I add a `.nojekyll` +file and rename the output directory to replace `docs`. + +Now the changes can be added, committed and pushed. Once pushed, the new code is +automatically served by GitHub Pages. + +## HTTPS + +GitHub Pages unfortunately does [not support HTTPS for custom domains][7]. + +As the site was previously using HTTPS, I didn’t want to have to go back to +HTTP, break any incoming links and lose any potential traffic. To continue using +HTTPS, I decided to [use Cloudflare][6] to serve the site via their CDN which +does allow for HTTPS traffic. + +## Next Steps + +- Enable automatically running `publish.sh` when new changes are pushed to + GitHub rather than running it manually. I was previously [using Jenkins][4] + and Fabric for this, though I’m also going to look into using Travis to + accomplish this. +- Add the pre-build steps such as running `composer install` and `yarn` to + install dependencies, and `gulp` to create the front-end assets. This was + previously done by Jenkins in my previous setup. + +## Resources + +- [Publishing your GitHub Pages site from a /docs folder on your master + branch][2] +- [Bypassing Jekyll on GitHub Pages][5] +- [Secure and fast GitHub Pages with CloudFlare][6] + +[0]: https://pages.github.com +[1]: https://github.com/opdavies/oliverdavies.uk +[2]: + https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/#publishing-your-github-pages-site-from-a-docs-folder-on-your-master-branch +[3]: https://github.com/opdavies/oliverdavies.uk/blob/master/publish.sh +[4]: /articles/2015/07/21/automating-sculpin-jenkins +[5]: https://github.com/blog/572-bypassing-jekyll-on-github-pages +[6]: https://blog.cloudflare.com/secure-and-fast-github-pages-with-cloudflare +[7]: https://github.com/blog/2186-https-for-github-pages diff --git a/source/_posts/queuing-private-messages-drupal-8.md b/source/_posts/queuing-private-messages-drupal-8.md new file mode 100644 index 00000000..9fcd1d1c --- /dev/null +++ b/source/_posts/queuing-private-messages-drupal-8.md @@ -0,0 +1,84 @@ +--- +title: Queuing Private Messages in Drupal 8 +date: 2018-02-27 +excerpt: Introducing the Private Message Queue module for Drupal 8. +tags: + - drupal + - drupal-8 + - drupal-modules + - drupal-planet + - open-source +--- + +My current project at [Microserve][0] is a Drupal 8 website that uses the +[Private Message][1] module for users to send messages to each other. + +In some cases though, the threads could contain hundreds of recipients so I +decided that it would be good to queue the message requests so that they can be +processed as part of a background process for better performance. The Private +Message module does not include this, so I've written and released a separate +[Private Message Queue][2] module. + +## Queuing a Message + +The module provices a `PrivateMessageQueuer` service +(`private_message_queue.queuer`) which queues the items via the `queue()` +method. + +The method accepts an array of `User` objects as the messsage recipients, the +message body text and another user as the message owner. (I’m currently +considering [whether to make the owner optional][4], and default to the current +user if one is not specified) + +Here is an example: + +```php +$recipients = $this->getRecipients(); // An array of User objects. +$message = 'Some message text'; +$owner = \Drupal::currentUser(); + +$queuer = \Drupal::service('private_message_queue.queuer'); +$queuer->queue($recipients, $message, $owner); +``` + +These three pieces of data are then saved as part of the queued item. You can +see these by checking the "queue" table in the database or by running +`drush queue-list`. + +![](/images/blog/private-message-queue.png) + +``` +$ drush queue-list +Queue Items Class +private_message_queue 19 Drupal\Core\Queue\DatabaseQueue +``` + +## Processing the Queue + +The module also provides a `PrivateMessageQueue` queue worker, which processes +the queued items. For each item, it creates a new private message setting the +owner and the message body. + +It uses the `PrivateMessageThread` class from the Private Message module to find +for an existing thread for the specified recipients, or creates a new thread if +one isn't found. The new message is then added to the thread. + +The queue is processed on each cron run, so I recommend adding a module like +[Ultimate Cron][3] so that you can process the queued items frequently (e.g. +every 15 minutes) and run the heavier tasks like checking for updates etc less +frequently (e.g. once a day). + +You can also process the queue manually with Drush using the +`drush queue-run ` command - e.g. +`drush queue-run private_message_queue`. + +``` +$ drush queue-run private_message_queue +Processed 19 items from the private_message_queue queue in 3.34 sec. +``` + +[0]: {{site.companies.microserve.url}} +[1]: https://www.drupal.org/project/private_message +[2]: https://www.drupal.org/project/private_message_queue +[3]: https://www.drupal.org/project/ultimate_cron +[4]: https://www.drupal.org/project/private_message_queue/issues/2948233 diff --git a/source/_posts/quick-project-switching-phpstorm.md b/source/_posts/quick-project-switching-phpstorm.md new file mode 100644 index 00000000..86b3c980 --- /dev/null +++ b/source/_posts/quick-project-switching-phpstorm.md @@ -0,0 +1,67 @@ +--- +title: Quick Project Switching in PhpStorm +date: 2018-09-04 +excerpt: How to quickly switch between projects in PhpStorm. +tags: + - phpstorm +has_tweets: true +--- + +Following a recent conversation on Twitter with +[socketwench](https://twitter.com/socketwench) about project switching in +PhpStorm, I thought I’d document my workflow here. + +Here is the original tweet and my initial response. I also have a lot of +PhpStorm projects, and as I’m always working on multiple projects I regularly +need to switch between them. + +{% include 'tweet' with { + content: '

I think you can start typing and it will filter?

— Oliver Davies (@opdavies) August 28, 2018', +} %} + +On the PhpStorm welcome screen that displays when you first open it, your recent +projects are displayed on the left-hand side of the screen, and are filterable. +That means that I can start typing a project name, e.g. `oli`, and I will only +see projects that start with that input. + +![The PhpStorm welcome screen with filters applied to the project list](/images/blog/quick-project-switching-phpstorm/welcome-screen.png){.with-border +.with-padding} + +That’s great when opening a project from scratch, but what about when we’re +already within a project and just want to be able to switch to another? + +{% include 'tweet' with { + content: '

You can also use 'Open recent' within the actions list, and then filter the list of projects. pic.twitter.com/k8G9iIQNP0

— Oliver Davies (@opdavies) August 28, 2018', +} %} + +There’s also a way to access this list once PhpStorm is open, by clicking 'Open +Recent' within the File menu. The issue here though is that this list is not +filterable. + +You can also access this list using the keyboard, though the 'Search everywhere' +or 'Find action' panes, and these are filterable. + +![Using the 'find action' pane to find 'Open Recent'](/images/blog/quick-project-switching-phpstorm/find-action.png){.with-border +.with-padding} + +Once the 'Open Recent' option is selected, you see the same project list as on +the welcome screen, which is filtered in the same way by starting to type +potential project names. + +![The filtered project list](/images/blog/quick-project-switching-phpstorm/open-recent.png){.with-border +.with-padding} + +## Adding a Keyboard Shortcut + +We can make this easier by adding a new keyboard shortcut. Within the Keymap +preferences, you can search for 'Open Recent' and right-click it to add a new +keyboard shortcut and define the key combination. + +![Finding the 'Open Recent' shortcut in the Keymap preferences](/images/blog/quick-project-switching-phpstorm/adding-keyboard-shortcut-1.png){.with-border +.with-padding} + +![Assigning a keyboard shortcut](/images/blog/quick-project-switching-phpstorm/adding-keyboard-shortcut-2.png){.with-border +.with-padding} + +This this shortcut added, you can now use it to instantly bring up your recent +projects list, filter it and switch project. diff --git a/source/_posts/quickest-way-install-sublime-text-2-ubuntu.md b/source/_posts/quickest-way-install-sublime-text-2-ubuntu.md new file mode 100644 index 00000000..96b67336 --- /dev/null +++ b/source/_posts/quickest-way-install-sublime-text-2-ubuntu.md @@ -0,0 +1,25 @@ +--- +title: The Quickest way to Install Sublime Text 2 in Ubuntu +date: 2013-03-02 +excerpt: After reading numerous blog posts about how to install Sublime Text 2 in Ubuntu, this is definitely the quickest way! +tags: + - linux + - sublime-text + - ubuntu +--- + +After reading numerous blog posts about how to install +[Sublime Text 2](http://www.sublimetext.com/2 'Sublime Text 2') in +[Ubuntu](http://www.ubuntu.com/2 'Ubuntu'), this is definitely the quickest way! + +Just paste the following lines into your Terminal: + +```bash +$ sudo add-apt-repository ppa:webupd8team/sublime-text-2 +$ sudo apt-get update +$ sudo apt-get install sublime-text +``` + +After running this, Sublime Text 2 has been installed within the +_/usr/lib/sublime-text-2_ directory and can be launched from the Dashboard, or +by typing `subl`, `sublime-text` or `sublime-text-2` into a Terminal window. diff --git a/source/_posts/quickly-apply-patches-using-git-curl-or-wget.md b/source/_posts/quickly-apply-patches-using-git-curl-or-wget.md new file mode 100644 index 00000000..4af01720 --- /dev/null +++ b/source/_posts/quickly-apply-patches-using-git-curl-or-wget.md @@ -0,0 +1,29 @@ +--- +title: Quickly Apply Patches Using Git and curl or wget +date: 2013-12-24 +excerpt: How to quickly download a patch file and apply it to a Git repository in one line. +tags: + - drupal-planet + - git +--- + +Testing a patch file is usually a two-step process. First you download the patch +file from the source, and then you run a separate command to apply it. + +You can save time and typing by running the two commands on one line: + +```bash +$ curl http://drupal.org/files/[patch-name].patch | git apply -v +``` + +Or, if you don't have curl installed, you can use wget: + +```bash +$ wget -q -O - http://drupal.org/files/[patch-name].patch | git apply -v +``` + +These commands need to be run within the root of your Git repository (i.e. where +the .git directory is). + +These snippets were taken from +[Applying Patches with Git](https://drupal.org/node/1399218) on Drupal.org. diff --git a/source/_posts/quickly-import-multiples-images-using-imagefieldimport-module.md b/source/_posts/quickly-import-multiples-images-using-imagefieldimport-module.md new file mode 100644 index 00000000..7bcab6b6 --- /dev/null +++ b/source/_posts/quickly-import-multiples-images-using-imagefieldimport-module.md @@ -0,0 +1,44 @@ +--- +title: Quickly Import Multiples Images Using the Imagefield_Import Module +date: 2010-05-29 +excerpt: How to use the Imagefield Import module. +tags: + - cck + - drupal + - drupal-6 + - drupal-planet + - imagefield + - imagefield-import + - photo-gallery +--- + +**Thanks to Bob at [Mustardseed Media](http://mustardseedmedia.com) for +[tweeting](http://twitter.com/mustardseedinc/status/14713096905) about this +module. It's undoubtedly saved me hours of work today alone!** + +I've recently started a personal project converting a website to Drupal. It's +currently a static HTML/CSS site which also uses the +[Coppermine Photo Gallery](http://coppermine-gallery.net). As part of building +the new website, I wanted to move all the photos from the existing site onto the +new one. However, with 1260 photos in 17 albums, this could have been a lengthy +process! + +I created a new Drupal-powered Gallery as described in +[this screencast](http://lullabot.com/articles/photo-galleries-views-attach) by +[Jeff Eaton](http://twitter.com/eaton) - using the CCK and Imagefield modules, +and re-created each of my existing Gallery nodes. Using the +[Imagefield_Import](http://drupal.org/project/imagefield_import) module, I was +then able to quickly import the photos into the new Galleries. + +I downloaded all the photos from the previous Gallery via FTP, and installed and +configured the Imagefield_Import module. + +I created an 'Import' folder, selected the target field and mode. In this case, +I want each image to be imported into its own Photo node. I moved the photos for +the first album into the Import folder, and loaded the 'Import Images' screen +(admin/content/imagefield_import). + +After clicking 'Import', a node is created for each photo, the image is +uploaded, and added to the selected Gallery. + +Just another 1248 photos to go... diff --git a/source/_posts/rebuilding-acquia-dashboard-with-vuejs-tailwind-css.md b/source/_posts/rebuilding-acquia-dashboard-with-vuejs-tailwind-css.md new file mode 100644 index 00000000..799d442e --- /dev/null +++ b/source/_posts/rebuilding-acquia-dashboard-with-vuejs-tailwind-css.md @@ -0,0 +1,163 @@ +--- +title: Rebuilding Acquia’s Dashboard with Vue.js and Tailwind CSS +excerpt: How I rebuilt Acquia’s dashboard using Vue.js and Tailwind CSS. +tags: + - drupal + - tailwind-css + - tweet + - vuejs +draft: true +date: ~ +promoted: true +--- + +After +[rebuilding Drupal’s Bartik theme](/blog/rebuilding-bartik-with-vuejs-tailwind-css), +I’ve now used [Vue.js][vue] and [Tailwind CSS][tailwind] to rebuild another +Drupal related UI - this time it’s [Acquia’s](https://www.acquia.com) web +hosting dashboard. Again, you can [view the site on Netlify][netlify] and [the +code on GitHub][github]. + +## Why? + +The same as the Bartik rebuild, this was a good opportunity for me to gain more +experience with new technologies - Vue in particular - and to provide another +demonstration of how Tailwind CSS can be used. + +Like the Bartik clone, this was originally going to be another single page +rebuild, however after completing the first page I decided to expand it to +include three pages which also gave me the opportunity to use +[Vue Router](https://router.vuejs.org) - something that I had not used +previously - and to organise a multi-page Vue application. + +## Configuring Vue Router + +`src/router/index.js`: + +```js +import Vue from 'vue'; +import Router from 'vue-router'; +import Applications from '@/views/Applications'; +import Environment from '@/views/Environment'; +import Environments from '@/views/Environments'; + +Vue.use(Router); + +export default new Router({ + routes: [ + { + path: '/', + name: 'applications', + component: Applications, + }, + { + path: '/:id/environments', + name: 'environments', + component: Environments, + props: true, + }, + { + path: '/:id/environments/:environmentName', + name: 'environment', + component: Environment, + props: true, + }, + ], +}); +``` + +## Passing in data + +`src/data.json` + +```json +{ + "applications": { + "1": { + "id": 1, + "name": "Rebuilding Acquia", + "machineName": "rebuildingacquia", + "type": "Drupal", + "level": "Enterprise", + "environments": { + "dev": { + "name": "Dev", + "url": "dev.rebuilding-acquia.com", + "label": "develop" + }, + "stage": { + "name": "Stage", + "url": "stg.rebuilding-acquia.com", + "label": "master" + }, + "prod": { + "name": "Prod", + "url": "rebuilding-acquia.com", + "label": "tags/2018-12-21" + } + }, + "tasks": [ + { + "text": "Commit: fdac923 Merge branch 'update-password-policy' refs/heads/master", + "user": "system", + "times": { + "display": "Dec 19, 2018 3:48:29 PM UTC +0000", + "started": "Dec 19, 2018 3:48:29 PM UTC +0000", + "completed": "Dec 19, 2018 3:48:29 PM UTC +0000" + }, + "loading": false, + "success": true + } + ] + } + } +} +``` + +## The Environments page + +This was the first page that I rebuilt - the Environments page for an +application that shows the information of the different configured environments. + +Vue Router is configured to show the + +{% include 'figure' with { + image: { + src: '/images/blog/rebuilding-acquia-vue-tailwind/3-environments.png', + alt: 'A screenshot of the rebuilt Environments page.', + }, + caption: 'The rebuilt Environments page for an application.', +} %} + +## The applications page + +{% include 'figure' with { + image: { + src: '/images/blog/rebuilding-acquia-vue-tailwind/1-applications-grid.png', + alt: 'The rebuild Applications page, with applications displayed in a grid.', + }, + caption: 'The rebuilt Applications page - grid view', +} %} + +{% include 'figure' with { + image: { + src: '/images/blog/rebuilding-acquia-vue-tailwind/2-applications-list.png', + alt: 'The rebuild Applications page, with applications displayed as a list.', + }, + caption: 'The rebuilt Applications page - list view', +} %} + +## An environment page + +{% include 'figure' with { + image: { + src: '/images/blog/rebuilding-acquia-vue-tailwind/4-environment.png', + alt: 'A screenshot of the rebuilt Environment page.', + }, + caption: 'The rebuilt page for an environment within an application.', +} %} + +[github]: https://github.com/opdavies/rebuilding-acquia +[netlify]: https://rebuilding-acquia.oliverdavies.uk +[tailwind]: https://tailwindcss.com +[vue]: https://vuejs.org diff --git a/source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css-part-2.md b/source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css-part-2.md new file mode 100644 index 00000000..0a100145 --- /dev/null +++ b/source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css-part-2.md @@ -0,0 +1,313 @@ +--- +title: Rebuilding Bartik (Drupal’s Default Theme) with Vue.js and Tailwind CSS - part 2 +date: 2018-12-27 +excerpt: A follow-up to my original post on rebuilding Bartik with Tailwind and Vue.js. +tags: + - drupal + - tailwind-css + - tweet + - vuejs +has_tweets: true +--- + +In [the original post](/blog/rebuilding-bartik-with-vuejs-tailwind-css) I +detailed how I built [a clone of Drupal’s Bartik theme][netlify] with +[Vue.js][vuejs] and [Tailwind CSS][tailwind]. This follow-up post details some +updates that I’ve made to it since then. + +## Customising Tailwind’s colours + +During the first version of the page, my thoughts were to not edit the Tailwind +configuration, however I changed my mind on this whilst working on the +subsequent updates and did make some changes and customisations to the +`tailwind.js` file. + +By default, Tailwind includes a full colour palette including colours such as +yellows, oranges, reds that weren’t being used in this page so they were +removed. This makes the file more readable as well as reduces the number of +classes that Tailwind generates. + +Whist I was changing the colours, I also took the opportunity to tweak the +values of the remaining colours to more closely match Bartik’s original colours. + +I also added a `black-60` class which uses +[RGBA](https://css-tricks.com/the-power-of-rgba) to provide a semi-transparent +background. I used this when adding the +[skip to main content link](#adding-the-skip-to-main-content-link). + +```js +let colors = { + transparent: 'transparent', + + black: '#22292f', + 'grey-darkest': '#3d4852', + 'grey-dark': '#8795a1', + grey: '#b8c2cc', + 'grey-light': '#dae1e7', + 'grey-lighter': '#f0f0f0', + 'grey-lightest': '#F6F6F2', + white: '#ffffff', + + 'black-60': 'rgba(0, 0, 0, .6)', + + 'blue-dark': '#2779bd', + blue: '#3490dc', + 'blue-light': '#bcdefa', + + 'green-dark': '#325E1C', + green: '#77B159', + 'green-light': '#CDE2C2', + 'green-lighter': '#F3FAEE', +}; +``` + +## Adding default styling for links + +In the first version, every link was individually styled which resulted in a lot +of duplicate classes and a potential maintenance issue. + +I added a `style` section within `Welcome.vue`, and added some default styling +for links based on their location on the page - +[extracting some Tailwind components](https://tailwindcss.com/docs/extracting-components). + +
+```html + +``` + +Within the `style` section, I’m able to use Tailwind’s custom `@apply` directive +to inject it’s rules into more traditional CSS, rather than needing to add them +onto every link. + +```vue-html + +``` + +
+ +## Extracting a Vue component for Drupal blocks + +As well as being able to extract re-usable components within Tailwind, the same +can be done within Vue. As the page could potentially have multiple sidebar +blocks, I extracted a `SidebarBlock` component which would act as a wrapper +around the block’s contents. + +```vue-html +// src/components/Sidebar.vue + + +``` + +The component provides the wrapping div and the appropriate classes in a single +easy-to-maintain location, and +[uses a slot](https://vuejs.org/v2/guide/components-slots.html) as a placeholder +for the main content. + +That means that within `Welcome.vue`, the markup within the `sidebar-block` tags +will be used as the block contents. + +```html + +

My block contents.

+
+``` + +## Adding the Skip to Main Content Link + +One thing +[that was missing](https://github.com/opdavies/rebuilding-bartik/issues/1) was +the 'Skip to main content link'. This an accessibility feature that allows for +users who are navigating the page using only a keyboard to bypass the navigation +links and skip straight to the main content if they wish by clicking a link that +is hidden and only visible whilst it’s focussed on. + +Here is the markup that I used, which is placed directly after the opening +`` tag. + +```html + +``` + +I initially tried to implement the same feature on this website using +[Tailwind’s visually hidden plugin](https://www.npmjs.com/package/tailwindcss-visuallyhidden) +which also contains a `focussable` class, though I wasn’t able to style it the +way that I needed. I created my own +[Tailwind skip link plugin](https://www.npmjs.com/package/tailwindcss-skip-link) +and moved the re-usable styling there. + +To enable the plugin, I needed to add it within the `plugins` section of my +`tailwind.js` file: + +```js +plugins: [ + require('tailwindcss/plugins/container')(), + require('tailwindcss-skip-link')(), +], +``` + +I added only the page-specific styling classes to the link (as well as the +`skip-link` class that the plugin requires) as well as my own focus state to the +skip link that I did within the `style` section of `App.vue`. + +```vue-html + +``` + +![The Bartik clone with the skip to main content link visible](/images/blog/rebuilding-bartik-vue-tailwind-part-2/skip-link.png){.border} + +## Adding the DrupalMessage component + +I also added a version of Drupal’s status message as another Vue component. This +also uses a slot to include the message contents and accepts a +[prop](https://vuejs.org/v2/guide/components-props.html) for the message type. + +```html + +``` + +The value of the `type` prop is then used within some computed properties to +determine the type specific classes to add (e.g. green for success, and red for +warning), as well as whether or not to include the checkmark SVG image. + +```js + +``` + +I did need to make one change to the `tailwind.js` file in order to change the +border on links when they are hovered over - within `modules` I needed to enable +the `borderStyle` module for hover and focus states in order for Tailwind to +generate the additional classes. + +```js +modules: { + // ... + borderStyle: ['responsive', 'hover', 'focus'], + // ... +} +``` + +The message is included within the Welcome component by including the +`` element, though rather than importing it there, it’s +registed as a global component so it would be available to any other components +that could be added in the future. + +This is done within `main.js`: + +```js +// ... + +Vue.component('drupal-message', require('@/components/DrupalMessage').default); + +new Vue({ + render: h => h(App), +}).$mount('#app'); +``` + +![The Bartik clone with the Drupal Message component visible](/images/blog/rebuilding-bartik-vue-tailwind-part-2/drupal-message.png){.border} + +**The updated version is [live on Netlify][netlify], and the [latest source code +is available on GitHub][github].** + +[github]: https://github.com/opdavies/rebuilding-bartik +[netlify]: https://rebuilding-bartik.oliverdavies.uk +[tailwind]: https://tailwindcss.com +[vuejs]: https://vuejs.org diff --git a/source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css.md b/source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css.md new file mode 100644 index 00000000..2e8b0344 --- /dev/null +++ b/source/_posts/rebuilding-bartik-drupals-default-theme-vuejs-tailwind-css.md @@ -0,0 +1,345 @@ +--- +title: Rebuilding Bartik (Drupal’s Default Theme) with Vue.js and Tailwind CSS +date: 2018-11-20 +excerpt: How I rebuilt Drupal’s Bartik theme using Vue.js and Tailwind CSS. +tags: + - drupal + - tailwind-css + - tweet + - vuejs +has_tweets: true +--- + +Earlier this week, I built a clone of [Drupal][0]’s default theme, Bartik, with +[Vue.js][1] and [Tailwind CSS][2]. You can [view the code on GitHub][3] and the +[site itself on Netlify][4]. + +{% include 'tweet' with { + content: '

I built a clone of Bartik, #Drupal's default theme, with @vuejs and @tailwindcss. See the result at https://t.co/nPsTt2cawL, and the code at https://t.co/Dn8eysV4gf.

Blog post coming soon... pic.twitter.com/7BgqjmkCX0

— Oliver Davies (@opdavies) November 20, 2018', + data_cards: true, +} %} + +## Why build a Bartik clone? + +I’m a big fan of utility based styling and Tailwind CSS in particular, I was and +originally thinking of a way to more easily integrate Tailwind within Drupal - +something like I’ve since done with the [Tailwind CSS starter kit theme][5]. +Whilst thinking about that, I wondered about doing the opposite - rebuilding +Drupal (or Bartik) with Tailwind. + +Others including [Adam Wathan](https://adamwathan.me) (one of the creators of +Tailwind CSS) have rebuilt existing UIs like Netlify, YouTube, Twitter, Coinbase +and Transistor.fm with Tailwind as an opportunity for learning and also to +demonstrate using Tailwind - this was my opportunity to do the same. + +Whilst +[Drupal itself has adoped React](https://dri.es/drupal-looking-to-adopt-react), +I’ve personally been looking into Vue.js and have used it for some small +personal projects, including some elements of the site. So I decided to use Vue +for the interactive parts of my Bartik clone to create a fully functional clone +rather than focussing only on the CSS. + +## Building a static template with Tailwind + +The first stage was to build the desktop version, which was done as a simple +HTML file with Tailwind CSS pulled in from it’s CDN. This stage took just over +an hour to complete. + +As Tailwind was added via a CDN, there was no opportunity to customise it’s +configuration, so I needed to use to Tailwind’s default configuration for +colours, padding, spacing, fonts, breakpoints etc. The page is built entirely +with classes provided by Tailwind and uses no custom CSS, except for one inline +style that is used to add the background colour for the Search block, as there +wasn’t a suitable Tailwind option. + +When I decided that I was going to later add some interactivity onto the mobile +navigation menu, the existing code was ported into a new Vue.js application +generated by the Vue CLI, with the majority of the markup within a `Welcome` +component. This meant that Tailwind was also added as a dependency with it’s own +configuration file, though although I had the opportunity to customise it I +decided not to and made no changes to it and continued with the default values. + +`src/App.vue`: + +``` + + + + + +``` + +`src/components/Welcome.vue`: + +
+```vue-html + + + + +```` +
+ +## Making it responsive + +The second stage began with making the existing desktop version responsive - particularly making the navigation menu behave and appear differently on mobile and tablet screens, and stacking the main content area and the sidebar on mobile screens. This was all achieved using Tailwind’s responsive variants. + +```html +
+ ... +
+```` + +In this example, the `pb-4` class adds 1rem of bottom padding to the element by +default, then increases it to 3rem at large screen sizes due to the `lg:pb-12` +class. + +## Adding interactivity + +This is how the main navigation menu works on mobile: + +![The main navigation menu on mobile.](/images/blog/rebuilding-bartik-vue-tailwind/rebuilt-mobile.png) + +The show and hide text appears next to a hamburger menu, and clicking it toggles +the visiblity of the menu links which are stacked below, as well as the wording +of the text itself. + +The code for this was moved into a separate `MainMenu` component, which means +that it was easier to have dedicated data properties for whether the menu was +open or not, as well as computed properties for building the show/hide text. The +`open` value can then be used to apply the appropriate classes to the main menu +to toggle it. + +I also moved the links into `data` too - each link is it’s own object with it's +`title` and `href` values. This means that I can use a `v-for` directive to loop +over the data items and inject dynamic values, removing the duplication of +markup which makes the component easier to read and maintain. + +`src/components/MainMenu.vue`: + +
+ +```vue-html + + + +``` + +
+ +## The result + +The whole task only took around two hours to complete, and although some of the +colours and spacings are slightly different due to the decision to stick with +the default Tailwind configuration values, I’m happy with the result. + +### The original version + +![The original Bartik theme in a new installation of Drupal 8](/images/blog/rebuilding-bartik-vue-tailwind/original.png) + +### The Vue.js and Tailwind CSS version + +![The Vue.js/Tailwind CSS version, hosted on Netlify](/images/blog/rebuilding-bartik-vue-tailwind/rebuilt-desktop.png) + +
+I’ve also made some additional changes since this version, which are described in [this follow-up post](/blog/rebuilding-bartik-with-vuejs-tailwind-css-part-2). +
+ +[0]: https://www.drupal.org +[1]: https://vuejs.org +[2]: https://tailwindcss.com +[3]: https://github.com/opdavies/rebuilding-bartik +[4]: https://rebuilding-bartik.oliverdavies.uk +[5]: https://www.drupal.org/project/tailwindcss diff --git a/source/_posts/reflections-speaking-unifieddiff.md b/source/_posts/reflections-speaking-unifieddiff.md new file mode 100644 index 00000000..72eac389 --- /dev/null +++ b/source/_posts/reflections-speaking-unifieddiff.md @@ -0,0 +1,40 @@ +--- +title: Reflections on speaking at UnifiedDiff +date: 2012-09-06 +excerpt: Yesterday evening I went along and spoke at the UnifiedDiff meetup in Cardiff. +tags: + - speaking +--- + +Yesterday evening I went along and spoke at the +[UnifiedDiff meetup](http://www.unifieddiff.co.uk) in Cardiff, having offered +previously to do a presentation providing an introduction to Drupal. + +I'm an experienced Drupal Developer, but not an experienced public speaker +(although I have done several user training sessions and Drupal demonstrations +for clients previously), and I think that some of the nerves that I had +beforehand were apparent during the presentation, and being the first speaker +for the evening probably didn't help, although I did get a +[nice tweet](https://twitter.com/craigmarvelley/status/243418608720543745) +mid-way through. + +Initially, after aiming for a 20-minute presentation plus Q&A, I think I wrapped +up the presentation in around 14 minutes, although I did about 6 minutes of +answering questions afterwards including the apparently mandatory "Why use +Drupal compared to WordPress or Joomla?" question, some Drupal 8 and Symfony +questions, as well as an interesting question about the White House development +project after I'd listed it within a list of example sites. Next time, I think +that some more detailed presenter notes are needed. Typically, as soon as it sat +back in my seat, the majority of things that I'd managed to remember beforehand +all came flooding back to me and I thought "I should have said that whilst I was +up speaking". + +Overall, considering my inexperience at speaking to this type of audience, I was +fairly happy with my presentation, although I'm sure that I'll change my mind +once I've watched the video of it on the UnifiedDiff website. Regardless, I +think that it was a great experience and I enjoyed doing it, and I'd like to +thank the organisers of UnifiedDiff for having me speak at their meetup. It was +great to have a more relaxed conversation with some people after the other +speakers had been up, and having introduced Drupal I would be more than happy to +come back and do a more in-depth presentation if there is an interest for me to +do so. diff --git a/source/_posts/renaming-gray-grey-tailwind-css.md b/source/_posts/renaming-gray-grey-tailwind-css.md new file mode 100644 index 00000000..25194d35 --- /dev/null +++ b/source/_posts/renaming-gray-grey-tailwind-css.md @@ -0,0 +1,32 @@ +--- +title: Renaming gray to grey in Tailwind CSS +excerpt: How to change the colour "gray" to "grey" in Tailwind CSS. +tags: + - tailwind-css +date: 2020-09-04 +--- + +In `tailwind.config.js`: + +``` +const { colors } = require('tailwindcss/defaultTheme') + +module.exports = { + purge: ["./public/**/*.html"], + theme: { + extend: { + colors: { + // Remove the "gray" colours from the theme. + gray: {}, + + // Create a new set of "grey" colours, using the original "gray" values. + grey: colors['gray'] + } + }, + }, + variants: {}, + plugins: [], +}; +``` + +Based on a configuration file from https://github.com/tailwindlabs/tailwindcss-playground. diff --git a/source/_posts/restructuring-my-tailwindjs-configuration-files.md b/source/_posts/restructuring-my-tailwindjs-configuration-files.md new file mode 100644 index 00000000..59bc62c2 --- /dev/null +++ b/source/_posts/restructuring-my-tailwindjs-configuration-files.md @@ -0,0 +1,236 @@ +--- +title: Restructuring my tailwind.js configuration files +date: 2019-03-08 +excerpt: How I’ve started structuring my tailwind.js configuration files in preparation for Tailwind 1.0. +tags: + - laravel-mix + - tailwind-css +--- + +After watching Adam Wathan’s recent +["Working on Tailwind 1.0" YouTube video](https://www.youtube.com/watch?v=SkTKN38wSEM) +and seeing some of the proposed changes to the `tailwind.js` configuration file, +I’ve started to structure my current config files a little differently in +preparation for 1.0. + +## The current tailwind.js file format + +Currently when you run `tailwind init` to create a new config file, it includes +all of Tailwind’s default values, and then you can add, edit and remove values +as needed. + +Some values like colours, font families, plugins and modules you are likely to +change for each project, whilst others like shadows, leading, z-index and +opacity, you’re less likely to need to change. + +It’s 952 lines including comments, which is quite long and could potentially be +daunting for new Tailwind users. + +The contents of the full file can be found in the +[Tailwind CSS documentation](https://tailwindcss.com/docs/configuration#default-configuration), +or it can be found in +[various GitHub repositories](https://github.com/tailwindcss/plugin-examples/blob/master/tailwind.js). + +## A preview of the new tailwind.js file format + +In Adam’s [Laracon Online](https://laracon.net) talk, Tailwind CSS by Example, +he showed the new configuration file format. Here is a snippet: + +```js +module.exports { + theme: { + extend: { + spacing: { + 7: '1.75rem', + }, + }, + colors: { + white: { + default: '#fff', + 20: 'rgba(255,255,255,.2)', + 40: 'rgba(255,255,255,.4)', + 60: 'rgba(255,255,255,.6)', + 80: 'rgba(255,255,255,.8)', + }, + ... + } + ... + } +} +``` + +You’ll notice that the structure of the file is quite different, and that all of +the default values have been removed and are now maintained by Tailwind itself. + +This means that the configuration file contains only your custom changes, where +you've either overridden a default value (e.g. colours) or added your own using +`extend` (e.g. adding another spacing value, as in this example). + +I think that's a great improvement and makes the file so much cleaner, and +easier to read and understand. + +## An interim approach + +If you don’t want to wait until 1.0, or potentially 0.8, you can get some of +this functionality now by restructuring your Tailwind configuration file. + +Here is the complete `tailwind.js` file for the +[DrupalCamp Bristol 2019 static landing page](https://dcb-2019-static.netlify.com), +which uses Tailwind in addition to the existing traditional CSS: + +```js +let defaultConfig = require('tailwindcss/defaultConfig')(); + +var colors = { + ...defaultConfig.colors, + black: '#000', +}; + +module.exports = { + ...defaultConfig, + colors: colors, + textColors: colors, + backgroundColors: colors, + borderColors: Object.assign({ default: colors['grey-light'] }, colors), + plugins: [ + require('tailwindcss-interaction-variants')(), + require('tailwindcss-spaced-items'), + ], + modules: { + ...defaultConfig.modules, + textStyle: [...defaultConfig.modules.textStyle, 'hocus'], + }, + options: { + ...defaultConfig.options, + prefix: 'tw-', + important: true, + }, +}; +``` + +Here are the steps that I took to create this file: + +
    +
  1. +

    **Get the default configuration**. This is done using `require('tailwindcss/defaultConfig')()`. Essentially this has the same contents as the current `tailwind.js` file, though now it’s owned and maintained within Tailwind itself, and not by the user.

    +

    Also any new or updated values within the default configuration will be automatically available.

    +

    This line is present but commented out in the current generated `tailwind.js` file.

    +
  2. + +
  3. +

    **Create the colors object.** This will by default override Tailwind’s default colours, however you can add `...defaultConfig.colors` to include them and then add or edit values as needed.

    +

    In this example, I’m overridding the value used for the `black` colour classes to match the existing colour in the other CSS.

    +
  4. + +
  5. +

    **Return the main configuration object.** For sites with no overrides, this could just be `module.exports = defaultConfig` for a minimal configuration.

    +

    To extend the defaults, add `...defaultConfig` at the beginning.

    +
  6. + +
  7. +

    **Assign our colours.** Use them for `colors`, `textColors`, `backgroundColors` and `borderColours`.

    +
  8. + +
  9. +

    **Add any plugins**. I use plugins on most projects, in this case I’m using [tailwindcss-interaction-variants](https://www.npmjs.com/package/tailwindcss-interaction-variants) and [tailwindcss-spaced-items](https://www.npmjs.com/package/tailwindcss-spaced-items). Usually the default `container` plugin would be here too.

    +
  10. + +
  11. +

    **Add or override modules.** Here I’m adding the `hocus` (hover and focus) variant provided by the interaction variants plugin to the text style classes.

    +
  12. + +
  13. +

    **Add or override options.** As this markup was originally from a Drupal website, I needed to override some of the options values. I’ve added the `tw-` prefix to avoid Tailwind classes from clashing with Drupal’s default markup, and set all Tailwind classes to use `!important` so that they override any existing styles.

    +
  14. +
+ +This file is only 27 lines long, so considerably shorter than the default file, +and I think that it’s much easier to see what your additional and overridden +values are, as well able to quickly recognise whether a class is generated from +a custom value or from a Tailwind default value. + +To move this file to the new format I think would be much easier as there’s no +default configuration to filter out, and you can move across only what is +needed. + +## Other changes + +### Consistent spacing for padding and margin + +Similar to defining colours, you could also set some standard spacing values, +and using those for padding, margin and negative margin to ensure that they are +all consistent. + +In this case, we can use `defaultConfig.margin` to get the default, add or +override any values, and then assign it to the relevant sections of the main +object. + +```js +const spacing = { + ...defaultConfig.margin, + '2px': '2px', +}; + +module.exports = { + ...defaultConfig, + // ... + padding: spacing, + margin: spacing, + negativeMargin: spacing, + // ... +}; +``` + +### Picking values with lodash + +In the opposite to extending, if we wanted to limit the number of values within +a part of the configuration, we can do that too. I’d suggest using the +[pick method](https://lodash.com/docs/4.17.11#pick) provided by +[Lodash](https://lodash.com). + +From the documentation: + +> Creates an object composed of the picked object properties. + +For example, if we only wanted normal, medium and bold font weights: + +```js +module.exports = { + ...defaultConfig, + // ... + fontWeights: _.pick(defaultConfig.fontWeights, ['normal', 'medium', 'bold']), + // ... +}; +``` + +### Renaming the file + +Also in Tailwind 1.0, it seems that the configuration file name is changing from +`tailwind.js` to `tailwind.config.js`. + +If you use [Laravel Mix](https://laravel-mix.com) and the +[Laravel Mix Tailwind plugin](https://github.com/JeffreyWay/laravel-mix-tailwind) +like I do on this site (even though it’s a Sculpin site), it will look for a +`tailwind.js` file by default or you can specify whatever filename you need. + +Here is an excerpt of the Tailwind configuration file for this site, using +`tailwind.config.js`: + +```js +mix + .postCss('assets/css/app.css', 'source/dist/css') + .tailwind('tailwind.config.js'); +``` + +## Looking foward to Tailwind CSS 1.0! + +Adam has said that Tailwind 1.0 should be released within a few weeks of the +time of writing this, I assume once +[the 1.0 To-Do list](https://github.com/tailwindcss/tailwindcss/issues/692) is +completed. + +I really like some of the improvements that are coming in 1.0, including the new +configuration file format and the ability to easily add and extend values, as +well as the file itself now being completely optional. + +I can’t wait for it to land! diff --git a/source/_posts/review-adminhover-module.md b/source/_posts/review-adminhover-module.md new file mode 100644 index 00000000..fcca7695 --- /dev/null +++ b/source/_posts/review-adminhover-module.md @@ -0,0 +1,58 @@ +--- +title: Review of the Admin:hover Module +date: 2010-08-10 +excerpt: My review of Drupal’s admin:hover module. +tags: + - admin:hover + - administration + - drupal-6 + - drupal-modules + - drupal-planet +--- + +Sorry for the lack of Blog posts lately, but +[my new job](http://horseandcountry.tv) that I started a few weeks ago has +certainly been keeping me busy! I've got a few more posts that I'm preparing +content for, and I'll hopefully be back into my weekly-post routine before too +long! + +Today, I'd like to just give a quick overview of the +[Admin:hover](http://drupal.org/project/admin_hover) module. It basically adds +an administrative menu that pops up when you hover over a node or block within +your Drupal website - the kind of functionality that was present within previous +versions of the [Admin module](http://drupal.org/project/admin). It also +integrates well with the [Devel](http://drupal.org/project/devel) and +[Clone](http://drupal.org/project/node_clone) modules. + +I've found this to be extremely useful whilst working on photo galleries etc. +where multiple nodes are displayed in a grid format and I quickly need to +publish or unpublish something for testing purposes. No longer do I need to open +each node, or go into the administration area to perform the required actions. + +It is also possible to customise which links are available from within the +adminstration area. The possible selections that I currently have on this site +are as follows: + +**Node links:** + +- Edit +- Publish +- Unpublish +- Promote +- Unpromote +- Make sticky +- Make unsticky +- Delete +- Clone +- Dev load +- View author +- Edit author +- Add + +**Block links:** + +- Configure block +- Add block + +Although, as I have additional contributed modules installed, some of these may +not neccassaily be available out of the box. diff --git a/source/_posts/review-image-caption-module.md b/source/_posts/review-image-caption-module.md new file mode 100644 index 00000000..d7983ec0 --- /dev/null +++ b/source/_posts/review-image-caption-module.md @@ -0,0 +1,40 @@ +--- +title: Review of the Image Caption Module +date: 2010-08-20 +excerpt: My review of Drupal’s Image Caption module. +tags: + - drupal + - drupal-6 + - drupal-planet + - image-caption + - imagefield +--- + +Up until as recent as last week, whenever I added an image into one of my Blog +posts, I was manually adding the caption below each image and styling it +accordingly. That was until I installed the +[Image Caption](http://drupal.org/project/image_caption) module. + +The Image Caption module uses jQuery to dynamically add captions to images. Here +is a walkthrough of the process that I followed to install and configure the +module. As always, I used Drush to download and enable the module, then visited +the Image Caption Settings page (admin/settings/image_caption). Here, I select +which node types should be included in image captioning. In my case, I only +wanted this to apply to Blog posts. + +As I use the [FileField](http://drupal.org/project/filefield), +[ImageField](http://drupal.org/project/imagefield) and +[Insert](http://drupal.org/project/insert) modules to add images to my posts, as +opposed to via a WYSIWYG editor, I'm able to add the CSS class of 'caption' to +my images. + +Now, all images inserted this way will have the CSS class of 'caption'. + +As the Image Caption module uses the image's title tag to create the displayed +caption, I enabled the custom title text for my Image field so that when I +upload an image, I'm prompted to enter text for the caption. + +This results in a span called `image-caption-container` around the inserted +image, and a caption below it called `image-caption` containing the text. + +All that's left is to style these classes within your CSS stylesheet. diff --git a/source/_posts/review-teleport-module.md b/source/_posts/review-teleport-module.md new file mode 100644 index 00000000..3aa995c7 --- /dev/null +++ b/source/_posts/review-teleport-module.md @@ -0,0 +1,39 @@ +--- +title: Review of the Teleport Module +date: 2010-07-12 +excerpt: My review of Drupal’s Teleport module. +tags: + - drupal-planet + - drupal-6 + - drupal-modules + - teleport +--- + +As a heavily-reliant +[Quicksilver](http://en.wikipedia.org/wiki/Quicksilver_%28software%29) user on +my MacBook Pro, I was glad when I found the +[Teleport](http://drupal.org/project/teleport) module for +[Drupal](http://drupal.org) _(due to Elliott Rothman's +[tweet](http://twitter.com/elliotttt/status/18044234238))_. + +When you press a configurable hot-key, a jQuery dialog box appears where you can +search for nodes by title or path, or directly enter the path that you want to +navigate to. This will greatly reduce the number of clicks that I need to +perform to get to my desired page - even compared to the +[Admin](http://drupal.org/project/admin) and +[Administration Menu](http://drupal.org/project/admin_menu) modules. + +Although it's not a new module (the first commits were 2 years ago), I hope that +they are still planning on achieving the list of future directions listed on +their Drupal.org project page: + +- Make interface act more like Quicksilver (i.e. you should only have to press + Enter once to launch) +- 'Actions' like Quicksilver: if you select a node, a second input should appear + with options to go to the View page, Edit page, (un)publish, etc. Same with + users. +- Hook into more non-node content, like taxonomy terms and functions in the API + module. + +Personally, this will make navigation around both the front-end and +administration area of my Drupal sites so much easier. diff --git a/source/_posts/running-drupal-88-symfony-local-server.md b/source/_posts/running-drupal-88-symfony-local-server.md new file mode 100644 index 00000000..33de2ccc --- /dev/null +++ b/source/_posts/running-drupal-88-symfony-local-server.md @@ -0,0 +1,323 @@ +--- +title: Running Drupal 8.8 with the Symfony Local Server +excerpt: How to use Symfony's local web server to run a Drupal 8.8 website. +date: 2020-03-09 +tags: + - drupal + - drupal-8 + - symfony +--- + +![A screenshot of a terminal window running a Drupal project with the Symfony local server](/images/blog/running-drupal-with-symfony-local-server/terminal.png) + + + +## Installation + + + +The Symfony server is bundled as part of the `symfony` binary that is available +to download from . + +To install it, run this command: + +```bash +curl -sS https://get.symfony.com/cli/installer | bash +``` + +Even though it’s by Symfony, the local webserver works with any type of +project - including Drupal 8 (and 9) and Drupal 7. + +## Getting started + +Here are the basic commands to start and stop the server: + +```bash +# Alias for server:start, starts the server +symfony serve + +# Run the server in daemon mode (in the background) +symfony serve -d + +# Display the status of the server +symfony server:status + +# Stop the server +symfony server:stop +``` + +If your Drupal files are within a `web` or `docroot` directory, it will +automatically be used as the document root for the server, so files are served +from there if you run the serve command. + +If you use a different subdirectory name - one that isn't loaded automatically - +you can use the `--document-root` option: + +```bash +symfony serve --document-root www +``` + +## Different PHP Versions + +One of the most useful features of the Symfony server is that it +[supports multiple versions of PHP](https://symfony.com/doc/current/setup/symfony_server.html#different-php-settings-per-project) +if you have them installed, and a different version can be selected per +directory. + +This is done by adding a `.php-version` file to the root of the project that +contains the PHP version to use. For example: + +```bash +echo "7.3" > .php-version +``` + +Next time the server is started, this file will be read and the correct version +of PHP will be used. + +If you’re using macOS and want to install another version of PHP, you can do it +using Homebrew: + +```bash +# Install PHP 7.3 +brew install php@7.3 +``` + +[Further PHP customisations can be made per project](https://symfony.com/doc/current/setup/symfony_server.html#overriding-php-config-options-per-project) +by adding a `php.ini` file. + +## Securing Sites Locally + +The Symfony server allows for serving sites via HTTPS locally by installing its +own local certificate authority. + +If it’s not installed automatically, run this command to install it: + +``` +symfony server:ca:install +``` + +Now any site will be served via HTTPS by default, and any HTTP requests will be +automatically redirected. + +If you need to run a site with just HTTP, add the `--no-tls` option to the +`serve` command. + +## Adding Databases (and other services) with Docker + +The Symfony server has an integration with Docker for providing extra services - +such as databases that we’ll need to install Drupal. + +This is my `docker-compose.yaml` file which defines a `database` service for +MySQL: + +```yaml +version: '2.1' + +services: + database: + image: mysql:5.7 + ports: [3306] + environment: + MYSQL_ROOT_PASSWORD: secret + volumes: + - mysql-data:/var/lib/mysql + +volumes: + mysql-data: +``` + +Because port 3306 is exposed, the server recognises it as a database service and +automatically creates environment variables prefixed with `DATABASE_`. + +A list of all the environment variables can be seen by running +`symfony var:export` (add `| tr " " "\n"` if you want to view each one on a new +line, and `| sort` if you want to list them alphabetically): + +``` +DATABASE_DATABASE=main +DATABASE_DRIVER=mysql +DATABASE_HOST=127.0.0.1 +DATABASE_NAME=main +DATABASE_PASSWORD=secret +DATABASE_PORT=32776 +DATABASE_SERVER=mysql://127.0.0.1:32776 +DATABASE_URL=mysql://root:secret@127.0.0.1:32776/main?sslmode=disable&charset=utf8mb4 +DATABASE_USER=root +DATABASE_USERNAME=root +SYMFONY_DOCKER_ENV=1 +SYMFONY_TUNNEL= +SYMFONY_TUNNEL_ENV= +``` + +Now these environment variables can be used within `settings.php` file to allow +configure Drupal’s database connection settings: + +```php +// web/sites/default/settings.php + +if ($_SERVER['SYMFONY_DEFAULT_ROUTE_URL']) { + $databases['default']['default'] = [ + 'driver' => $_SERVER['DATABASE_DRIVER'], + 'host' => $_SERVER['DATABASE_HOST'], + 'database' => $_SERVER['DATABASE_NAME'], + 'username' => $_SERVER['DATABASE_USER'], + 'password' => $_SERVER['DATABASE_PASSWORD'], + 'port' => $_SERVER['DATABASE_PORT'], + 'prefix' => '', + 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', + 'collation' => 'utf8mb4_general_ci', + ]; +} +``` + +To keep things organised, I usually like to split these settings into their own +file and include it: + +```php +if ($_SERVER['SYMFONY_DEFAULT_ROUTE_URL'] && file_exists(__DIR__ . '/settings.symfony.php')) { + require_once __DIR__ . '/settings.symfony.php'; +} +``` + +## Installing Drupal + +Now that Drupal can connect to the (empty) database, we can install the site. I +usually do this using Drush, which is added as a dependency via Composer. + +The command that I’d usually run is: + +```bash +cd web + +../vendor/bin/drush site-install +``` + +However, this will cause an error like this because Drupal cannot connect to the +database when Drush is run in this way. + +> Error: Class 'Drush\Sql\Sql' not found in Drush\Sql\SqlBase::getInstance() + +To fix this, ensure that the command is prefixed with `symfony php`. This will +ensure that the correct PHP version and configuration is used, and that the +appropriate environment variables are available. + +```bash +symfony php ../vendor/bin/drush site-install +``` + +This also applies to all other Drush commands. + +## Custom Domain Names + +Currently we can only access the site via the localhost URL with a specific +port. The port is determined automatically when the server is started so it can +change if you have multiple projects running. + +Symfony server also allows for +[adding local domain names through a proxy](https://symfony.com/doc/current/setup/symfony_server.html#local-domain-names). +This is useful if you always want to access the site from the same URL, or if +the site relies on using a specific URL such as a multisite setup (multiple +domains served from the same codebase). + +{% include 'figure' with { + image: { + src: '/images/blog/running-drupal-with-symfony-local-server/proxy.png', + alt: 'A screenshot of the proxy overview screen, showing three local projects with their local domains, ports and directories.', + }, + caption: 'The proxy overview screen' +} only %} + +### Setting up a multisite + +Here’s an example of how I would use local domains to configure a multisite +Drupal installation (taken from +). + +The first thing is to add the subdomain to the proxy. In this example, I’m going +to set up a version of the Umami demo installation profile at +`https://umami.wip`. + +```bash +# Add umami.wip to the proxy and attach it to this directory +symfony proxy:domain:attach umami +``` + +Now we can add it to Drupal’s `sites.php` file to route requests to the correct +site directory: + +```php +// web/sites/sites.php + +// This maps https://umami.wip to the sites/umami directory +$sites['umami.wip'] = 'umami'; +``` + +To create the directory, we can duplicate the `default` site directory and its +contents. + +``` +cp -R web/sites/default web/sites/umami +``` + +To create a separate database, we add a new service to the `docker-compose.yaml` +file and a new MySQL volume to store the data. We can use labels to generate +site specific environment variables. + +```diff + version: '2.1' + + services: + database: + image: mysql:5.7 + ports: [3306] + environment: + MYSQL_ROOT_PASSWORD: secret + volumes: + - mysql-data:/var/lib/mysql + ++ database_umami: ++ image: mysql:5.7 ++ ports: [3306] ++ environment: ++ MYSQL_ROOT_PASSWORD: secret ++ volumes: ++ - mysql-data-umami:/var/lib/mysql ++ labels: ++ com.symfony.server.service-prefix: 'UMAMI_DATABASE' + + volumes: + mysql-data: ++ mysql-data-umami: +``` + +These can then be added to `sites/umami/settings.php`: + +```php +$databases['default']['default'] = [ + 'driver' => $_SERVER['UMAMI_DATABASE_DRIVER'], + 'host' => $_SERVER['UMAMI_DATABASE_HOST'], + 'database' => $_SERVER['UMAMI_DATABASE_NAME'], + 'username' => $_SERVER['UMAMI_DATABASE_USER'], + 'password' => $_SERVER['UMAMI_DATABASE_PASSWORD'], + 'port' => $_SERVER['UMAMI_DATABASE_PORT'], + 'prefix' => '', + 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', + 'collation' => 'utf8mb4_general_ci', +]; +``` + +Now that the Umami site is able to connect to its own database, we can install +Drupal - specifying the installation profile to use and also the site directory +to target. + +```bash +symfony php ../vendor/bin/drush site-install \ + demo_umami \ + -l umami \ + --no-interaction +``` diff --git a/source/_posts/sculpin-twig-resources.md b/source/_posts/sculpin-twig-resources.md new file mode 100644 index 00000000..0aeb7915 --- /dev/null +++ b/source/_posts/sculpin-twig-resources.md @@ -0,0 +1,51 @@ +--- +title: Sculpin and Twig Resources +date: 2015-07-19 +excerpt: A list of resources that I compiled whilst preparing for my Sculpin and Twig talk at DrupalCamp North. +tags: + - drupalcamp + - drupalcamp-north + - sculpin + - twig +--- + +Here’s a list of resources that I compiled whilst preparing for my +[Sculpin and Twig talk](http://drupalcampnorth.org/session/test-drive-twig-sculpin) +at [DrupalCamp North](http://drupalcampnorth.org). + +## General Information + +- +- + +## Where to Get Sculpin + +- +- +- +- + +## Source Code Examples + +- +- - the source repository for this + site. +- +- +- +- +- +- +- Google for "`sculpin_site.yml site:github.com`" for more examples. + +## Videos + +- - a YouTube playlist of Sculpin videos. + +## Twig + +- +- - variables, filters, + functions, template inheritance, expressions etc. +- Go to http://twig.sensiolabs.org/{foo} to search for a tag, filter, test or + function. diff --git a/source/_posts/simplifying-drupal-migrations-xautoload.md b/source/_posts/simplifying-drupal-migrations-xautoload.md new file mode 100644 index 00000000..d5792ed3 --- /dev/null +++ b/source/_posts/simplifying-drupal-migrations-xautoload.md @@ -0,0 +1,135 @@ +--- +title: Simplifying Drupal Migrations with xautoload +date: 2016-05-03 +excerpt: How to use the xautoload module to autoload migration classes within your Drupal 7 migration modules. +tags: + - autoloading + - drupal + - drupal-7 + - drupal-planet + - php +--- + +How to use the [xautoload][1] module to autoload migration classes within your +Drupal 7 migration modules. + +## What is xautoload? + +[xautoload][1] is a Drupal module that enables the autoloading of PHP classes, +in the same way that you would do so in a [Composer][2] based project such as +Drupal 8 or Symfony. + +It supports both the [PSR-0][3] and [PSR-4][4] standards, as well as providing a +wildcard syntax for Drupal’s `file[]` syntax in .info files. + +To use it, download and enable it from Drupal.org as you would for any other +module, and then add it as a dependency within your module. The xautoload +project page suggests including a minimum version in this format: + +```ini +dependencies[] = xautoload (>= 7.x-5.0) +``` + +This will ensure that the version of xautoload is 7.x-5.0 or newer. + +## How to use it + +### Wildcard syntax for .info files + +Here is an example .info file for a migrate module. + +```ini +; foo_migrate.info + +name = Foo Migration +core = 7.x +package = Foo + +files[] = includes/user.inc +files[] = includes/nodes/article.inc +files[] = includes/nodes/page.inc +``` + +In this example, each custom migration class is stored in it’s own file within +the `includes` directory, and each class needs to be loaded separately using the +`files[] = filename` syntax. + +One thing that the xautoload module does to enable for the use of wildcards +within this syntax. By using wildcards, the module file can be simplified as +follows: + +```ini +files[] = includes/**/*.inc +``` + +This will load any .inc files within the `includes` directory as well as any +sub-directories, like 'node' in the original example. + +This means that any new migration classes that are added will be automatically +loaded, so you don’t need to declare each include separately within +foo_migrate.info again. The great thing about this approach is that it works +with the existing directory and file structure. + +### Use the PSR-4 structure + +If you want to use the [PSR-4][4] approach, you can do that too. + +In order to do so, you’ll need to complete the following steps: + +1. Rename the `includes` directory to `src`. +2. Ensure that there is one PHP class per file, and that the file extension is + `.php` rather than `.inc`. +3. Ensure that the name of the file matches the name of the class - + `FooArticleNodeMigration` would be in a file called + `FooArticleNodeMigration.php`. +4. Add a namespace to each PHP file. This uses the same format as Drupal 8, + including the machine name of the module. For example, `Drupal\foo_migrate`. + - If the class is within a sub-directory, then this will also need to be + included within the namespace - e.g. `Drupal\foo_migrate\Node`. + - You’ll also need to import any class names that you are referencing, + including class names that are you extending, by adding `use` statements at + the top of the file. You may be able to prefix it with `\` instead (e.g. + `\DrupalNode6Migration`), but I prefer to use imports. + +Now your class may look something like this: + +```php + 'Drupal\foo_migrate\Node\FooArticleNodeMigration', + 'source_type' => 'story', + 'destination_type' => 'article', +); +``` + +## Resources + +- [xautoload module][1] +- [migrate module][5] +- [migrate_d2d module][6] +- [PSR-0][3] +- [PSR-4][4] + +[1]: https://www.drupal.org/project/xautoload +[2]: http://getcomposer.org +[3]: http://www.php-fig.org/psr/psr-0/ +[4]: http://www.php-fig.org/psr/psr-4/ +[5]: https://www.drupal.org/project/migrate +[6]: https://www.drupal.org/project/migrate_d2d diff --git a/source/_posts/site-upgraded-drupal-7.md b/source/_posts/site-upgraded-drupal-7.md new file mode 100644 index 00000000..de4ea387 --- /dev/null +++ b/source/_posts/site-upgraded-drupal-7.md @@ -0,0 +1,22 @@ +--- +title: Site Upgraded to Drupal 7 +date: 2012-01-04 +excerpt: As the vast majority of the Drupal websites that I currently work on are built on Drupal 7, I thought that it was time that I upgraded this site. +tags: + - drupal +--- + +As the vast majority of the Drupal websites that I currently work on are built +on Drupal 7, I thought that it was time that I upgraded this site. Following the +[core upgrade process](http://drupal.org/node/570162) and the +[CCK migration process](http://drupal.org/node/1144136), everything was upgraded +smoothly without any issues. + +I've upgraded a handful of essential contrib modules to the latest stable +version, [Administration Menu](http://drupal.org/project/admin_menu), +[Views](http://drupal.org/project/views) etc., and will continue upgrading the +other modules on the site as time allows. + +I also prefer [Bartik](http://drupal.org/project/bartik) to +[Garland](http://drupal.org/project/garland) - but I will be creating a new +custom theme when I get a chance. diff --git a/source/_posts/some-useful-git-aliases.md b/source/_posts/some-useful-git-aliases.md new file mode 100644 index 00000000..339b67d3 --- /dev/null +++ b/source/_posts/some-useful-git-aliases.md @@ -0,0 +1,34 @@ +--- +title: Some Useful Git Aliases +date: 2014-01-15 +excerpt: Here are some bash aliases that I use and find helpful for quickly writing Git and Git Flow commands. +tags: + - git +--- + +Here are some bash aliases that I use and find helpful for quickly writing Git +and Git Flow commands. + +These should be placed within your `~/.bashrc` or `~/.bash_profile` file: + +```bash +alias gi="git init" +alias gcl="git clone" +alias gco="git checkout" +alias gs="git status" +alias ga="git add" +alias gaa="git add --all" +alias gc="git commit" +alias gcm="git commit -m" +alias gca="git commit -am" +alias gm="git merge" +alias gr="git rebase" +alias gps="git push" +alias gpl="git pull" +alias gd="git diff" +alias gl="git log" +alias gfi="git flow init" +alias gff="git flow feature" +alias gfr="git flow release" +alias gfh="git flow hotfix" +``` diff --git a/source/_posts/some-useful-links-using-simpletest-drupal.md b/source/_posts/some-useful-links-using-simpletest-drupal.md new file mode 100644 index 00000000..9f6f5a23 --- /dev/null +++ b/source/_posts/some-useful-links-using-simpletest-drupal.md @@ -0,0 +1,19 @@ +--- +title: Some useful links for using SimpleTest in Drupal +date: 2013-06-13 +excerpt: Here are some useful links that I've found when researching about unit testing in Drupal using SimpleTest. +tags: + - drupal + - drupal-planet + - simpletest + - tdd + - test-driven-development + - testing +--- + +- [An Introduction to Unit Testing in Drupal](http://www.lullabot.com/blog/articles/introduction-unit-testing-drupal 'An Introduction to Unit Testing in Drupal') +- [Module Developer's Guide to SimpleTest](http://www.lullabot.com/blog/articles/drupal-module-developers-guide-simpletest "Module Developer's Guide to SimpleTest") +- [SimpleTest Tutorial (Drupal 6)](https://drupal.org/simpletest-tutorial 'SimpleTest Tutorial (Drupal 6)') +- [SimpleTest Tutorial (Drupal 7)](https://drupal.org/simpletest-tutorial-drupal7 'SimpleTest Tutorial (Drupal 7)') +- [SimpleTest Reference](https://drupal.org/node/278126 'SimpleTest Reference') +- [Testing with SimpleTest](https://drupal.org/node/1128366 'Testing with SimpleTest') diff --git a/source/_posts/south-wales-drupal-user-group.md b/source/_posts/south-wales-drupal-user-group.md new file mode 100644 index 00000000..30fedffa --- /dev/null +++ b/source/_posts/south-wales-drupal-user-group.md @@ -0,0 +1,20 @@ +--- +title: The Inaugural Meetup for the South Wales Drupal User Group +date: 2010-09-26 +excerpt: If you do Drupal and you're in the area, come and join us for the first SWDUG meetup! +tags: + - drupal + - drupal-planet + - meetups + - swdug +--- + +If you do Drupal and you're in the area, come and join us for the first SWDUG +meetup! + +We'll be meeting in the communal area just outside of the +[SubHub](http://www.subhub.com) HQ, at: + +4, The Studios
3 Burt Street
Cardiff
CF10 5FZ + +For more information and to signup, visit . diff --git a/source/_posts/speaking-drupalcon-amsterdam.md b/source/_posts/speaking-drupalcon-amsterdam.md new file mode 100644 index 00000000..8bf23594 --- /dev/null +++ b/source/_posts/speaking-drupalcon-amsterdam.md @@ -0,0 +1,39 @@ +--- +title: Speaking at DrupalCon Amsterdam +date: 2019-07-25 +excerpt: I’m going to be attending DrupalCon Europe again this year, but for the first time as a speaker. +tags: + - drupalcon + - personal + - speaking +has_tweets: true +--- + +

I’ve attended numerous DrupalCons since my first in Prague in 2013, as a delegate, as a [{{site.companies.drupal_association.name}}]({{site.companies.drupal_association.url}}) staff member, and also as a contribution sprint mentor. I’m excited to be attending DrupalCon Amsterdam again this year - but as my first time as a DrupalCon speaker.

+ +{% include 'tweet' with { + content: '

Super excited to be giving my first @DrupalConEur talk!#drupal #drupalcon #php #ansible https://t.co/5ZOPClUjvC pic.twitter.com/TWih82Ny0P

— Oliver Davies (@opdavies) July 16, 2019' +} %} + +The session that I’m going to be presenting is a twenty minute version of my +[Deploying PHP applications with Ansible, Ansible Vault and Ansistrano](/talks/deploying-php-ansible-ansistrano) +talk. + +{% include 'figure' with { + image: { + src: '/images/blog/speaking-drupalcon-amsterdam/drupalcon-schedule.jpg', + alt: 'My session on the DrupalCon Amsterdam schedule.', + }, + caption: 'My session on the DrupalCon Amsterdam schedule.', +} %} + +I’ve been working with Drupal since 2007 (or maybe 2008), and it was the subject +of my [first meetup talk](/talks/so-what-is-this-drupal-thing) in 2012. Since +then I’ve given 48 more talks +(including one workshop) at various user groups and conferences on a range of +development and systems administration topics. So it’s a nice conincedence that +this will be my fiftieth (50th) talk. + +Thanks also to my employer, +[{{site.companies.inviqa.name}}]({{site.companies.inviqa.url}}), who are giving +me the time and covering my costs to attend the conference. diff --git a/source/_posts/speaking-drupalcon-europe-2020.md b/source/_posts/speaking-drupalcon-europe-2020.md new file mode 100644 index 00000000..8be4cab7 --- /dev/null +++ b/source/_posts/speaking-drupalcon-europe-2020.md @@ -0,0 +1,17 @@ +--- +title: Speaking at DrupalCon Europe 2020 +excerpt: I'm excited to be speaking again at DrupalCon, this time online at DrupalCon Europe. +tags: + - drupal + - conferences + - speaking +date: 2020-07-30 +--- + +After giving my [Ansible and Ansistrano talk](/talks/deploying-php-ansible-ansistrano) in Amsterdam, I'm excited that another of my talks has been accepted for DrupalCon! + +This year, my [TDD - Test-Driven Drupal](/talks/tdd-test-driven-drupal) talk has been accepted for DrupalCon Europe, will is being held online from December 8-11th. + +I first gave this talk at DrupalCamp London 2017 and again a number of times over the last few years including at Drupal Developer Days in Lisbon and most recently for the North West (UK) Drupal user group in May. I've always had good feedback from it, and enjoy teaching others about testing and hopefully continue to inspire people to start writing tests themselves. + +This is definitely one of my favourite topics. I've enjoyed updating and improving this talk over the years, and I'm looking forward to giving it at DrupalCon this year. diff --git a/source/_posts/speaking-remotely-during-covid-19.md b/source/_posts/speaking-remotely-during-covid-19.md new file mode 100644 index 00000000..c72af93c --- /dev/null +++ b/source/_posts/speaking-remotely-during-covid-19.md @@ -0,0 +1,84 @@ +--- +title: Speaking remotely during COVID-19 +excerpt: I've been quite busy during this lockdown, giving talks remotely at conferences and user groups. +date: 2020-07-07 +tags: + - speaking +--- + +I've been quite busy during COVID-19 and various lockdowns, giving talks remotely at conferences and user groups. + +In mid-April, I send a tweet with an open offer to any user groups that needed a speaker, with some suggestions for talks that I'd given recently that I could present remotely. + + + +As well as this, I also applied to some open calls for papers for remote conferences, such as [CMS Philly](https://cmsphilly.org "The CMS Philly conference") (formerly Drupaldelphia) that was taking place online this year. + +At the time of writing, these are the talks that I've given remotely or are already planned for future dates. I'll be updating this list going forward as new talks are added, as well as my [talks page](/talks "My upcoming and past talks"). + +If you'd like me to speak at your online conference or user group and be added to this list, please contact me and we can see if we can find a suitable date. + +## Test-Driven Drupal + +An overview of automated testing in Drupal, and a demo of building a new Drupal 8 (or 9) module using test driven development. + +- [NWDUG](http://nwdrupal.org.uk) - 11th May +- [BADCamp 2020](https://2020.badcamp.org/session/tdd-test-driven-drupal) - 16th October +- [DrupalCon Europe 2020](https://events.drupal.org/europe2020/sessions/tdd-test-driven-drupal) - 8th December + +## Deploying PHP with Ansible and Ansistrano + +How to use Ansible, Ansible Vault and Ansistrano to deploy PHP applications, using a Drupal 8 application for a demo. + +- [Drupal Edinburgh](https://www.meetup.com/Drupal-Edinburgh/events/267905594) - 11th March +- [CMS Philly](https://cmsphilly.org) - 30th April +- [Drupal Yorkshire](https://www.meetup.com/DrupalYorkshire/events/zwzsfpybchbcc) - 20th May +- [PHP London](https://www.meetup.com/phplondon/events/270930524) - 4th June +- [PHP North East](https://www.meetup.com/phpnortheast) - 16th June +- [PHP Sussex](https://www.meetup.com/PHP-Sussex) - 1st July +- [Midwest PHP 2021](https://midwestphp.org/talks/1q5XUF2tTdXXLYOoujMkpF/Deploying_PHP_applications_with_Ansible,_Ansible_Vault_and_Ansistrano) - 23rd April 2021 + +## Taking Flight with Tailwind CSS + +An introduction to utility-based CSS and how to use Tailwind CSS in PHP projects using tools such as Webpack Encore and Laravel Mix. + +- [CMS Philly](https://cmsphilly.org) - 30th April +- [PHP Hampshire](https://www.meetup.com/meetup-group-yzpbvTYv) - 8th July +- [Drupal Yorkshire](https://www.meetup.com/DrupalYorkshire/events/zwzsfpybclbbc) - 20th August +- [DigitalCamp Atlanta](https://www.drupalcampatlanta.com/2020/sessions/taking-flight-tailwind-css) - 11th September +- [Bristol JS](https://techtalks.io/events/f8e26038-2561-484e-8a74-7a1e3a0369b8) - 30th September +- [Drupal Virtual Cafe](https://groups.drupal.org/node/536142) (Drupal Kyiv) - 15th October +- [PHP Cambridge](https://www.meetup.com/phpcambridge/events/273686561) - 19th January 2021 +- [Nashville PHP](https://www.meetup.com/nashvillephp/events/kzkdwryccdbmb) - 9th February 2021 + +## Updating to Drupal 9 + +How to update your site to Drupal 9, and why it's much different to any major Drupal version upgrade before! + +- [Drupal NYC](https://ti.to/drupalnyc/meetup-2020-08-05) - 2nd September +- [Leeds PHP](https://www.meetup.com/leedsphp/events/272504993) - 23rd September +- [Midwest PHP 2021](https://midwestphp.org/talks/7C0m4I87vq72cDoXvsHFRp/Upgrading_your_site_to_Drupal_9) - 22nd April 2021 + +## Working with Workspace + +- [NWDUG](https://www.meetup.com/nwdrupal/events/272098270) - 11th August (lightning talk) +- [PHP South West](https://www.meetup.com/php-sw/events/272787346) - 9th September (lightning talk) +- PHP North West - 2nd February 2021 + +## Automated Testing and Test-Driven Development in Drupal 8 (workshop) + +- [DrupalCamp London](https://drupalcamp.london/training/Automated-Testing-and-Test-Driven-Development-in-Drupal-8) - 13th March (in-person, just before UK lockdown) +- [DrupalCamp NYC](https://2020.drupalcamp.nyc/training/automated-testing-and-test-driven-development-drupal-8) - 14th November + +## Building Slides and Presenting with rst2pdf + +- [PHP South Wales](https://www.meetup.com/PHP-South-Wales/events/275625320) - January 28th 2021 + +## Soaring with Utility CSS and Tailwind (workshop) + +- [DrupalCamp Florida 2021](https://www.fldrupal.camp/training/soaring-utility-css-and-tailwind) - Feburary 18th 2021 + +## Building Static Websites with Sculpin + +- [Drupal Yorkshire](https://www.meetup.com/DrupalYorkshire/events/280100968) - 19th August 2021 +- PHP North West - 7th September diff --git a/source/_posts/splitting-new-drupal-project-from-repo.md b/source/_posts/splitting-new-drupal-project-from-repo.md new file mode 100644 index 00000000..4805617d --- /dev/null +++ b/source/_posts/splitting-new-drupal-project-from-repo.md @@ -0,0 +1,163 @@ +--- +title: How to split a new Drupal contrib project from within another repository +date: 2018-03-10 +excerpt: How to use Git to split a directory from within an existing repository into it’s own. +tags: + - drupal + - drupal-7 + - drupal-8 + - drupal-planet + - git + - open-source +--- + +Yay! You’ve written a new Drupal module, theme or installation profile as part +of your site, and now you’ve decided to open source it and upload it to +Drupal.org as a new contrib project. But how do you split it from the main site +repository into it’s own? + +Well, there are a couple of options. + +## Does it need to be part of the site repository? + +An interesting thing to consider is, does it _need_ to be a part of the site +repository in the first place? + +If from the beginning you intend to contribute the module, theme or distribution +and it’s written as generic and re-usable from the start, then it _could_ be +created as a separate project on Drupal.org or as a private repository on your +Git server from the beginning, and added as a dependency of the main project +rather than part of it. It could already have the correct branch name and adhere +to the Drupal.org release conventions and be managed as a separate project, then +there is no later need to "clean it up" or split it from the main repo at all. + +This is how I worked at the [Drupal Association][2] - with all of the modules +needed for Drupal.org hosted on Drupal.org itself, and managed as a dependency +of the site repository with Drush Make. + +Whether this is a viable option or not will depend on your processes. For +example, if your code needs to go through a peer review process before releasing +it, then pushing it straight to Drupal.org would either complicate that process +or bypass it completely. Pushing it to a separate private repository may depend +on your team's level of familiarity with [Composer][3], for example. + +It does though avoid the “we’ll clean it up and contribute it later” scenario +which probably happens less than people intend. + +## Create a new, empty repository + +If the project is already in the site repo, this is probably the most common +method - to create a new, empty repository for the new project, add everything +to it and push it. + +For example: + +```bash +cd web/modules/custom/my_new_module + +# Create a new Git repository. +git init + +# Add everything and make a new commit. +git add -A . +git commit -m 'Initial commit' + +# Rename the branch. +git branch -m 8.x-1.x + +# Add the new remote and push everything. +git remote add origin username@git.drupal.org:project/my_new_module.git +git push origin 8.x-1.x +``` + +There is a huge issue with this approach though - **you now have only one single +commit, and you’ve lost the commmit history!** + +This means that you lose the story and context of how the project was developed, +and what decisions and changes were made during the lifetime of the project so +far. Also, if multiple people developed it, now there is only one person being +attributed - the one who made the single new commit. + +Also, if I’m considering adding your module to my project, personally I’m less +likely to do so if I only see one "initial commit". I’d like to see the activity +from the days, weeks or months prior to it being released. + +What this does allow though is to easily remove references to client names etc +before pushing the code. + +## Use a subtree split + +An alternative method is to use [git-subtree][0], a Git command that "merges +subtrees together and split repository into subtrees". In this scenario, we can +use `split` to take a directory from within the site repo and split it into it’s +own separate repository, keeping the commit history intact. + +Here is the description for the `split` command from the Git project itself: + +> Extract a new, synthetic project history from the history of the +> subtree. The new history includes only the commits (including merges) that +> affected , and each of those commits now has the contents of +> at the root of the project instead of in a subdirectory. Thus, the newly +> created history is suitable for export as a separate git repository. + +
+__Note__: This command needs to be run at the top level of the repository. Otherwise you will see an error like "You need to run this command from the toplevel of the working tree.". + +To find the path to the top level, run `git rev-parse --show-toplevel`. + +
+ +In order to do this, you need specify the prefix for the subtree (i.e. the +directory that contains the project you’re splitting) as well as a name of a new +branch that you want to split onto. + +``` +git subtree split --prefix web/modules/custom/my_new_module -b split_my_new_module +``` + +When complete, you should see a confirmation message showing the branch name and +the commit SHA of the branch. + +``` +Created branch 'split_my_new_module' +7edcb4b1f4dc34fc3b636b498f4284c7d98c8e4a +``` + +If you run `git branch`, you should now be able to see the new branch, and if +you run `git log --oneline split_my_new_module`, you should only see commits for +that module. + +If you do need to tidy up a particular commit to remove client references etc, +change a commit message or squash some commits together, then you can do that by +checking out the new branch, running an interactive rebase and making the +required amends. + +``` +git checkout split_my_new_module +git rebase -i --root +``` + +Once everything is in the desired state, you can use `git push` to push to the +remote repo - specifying the repo URL, the local branch name and the remote +branch name: + +``` +git push username@git.drupal.org:project/my_new_module.git split_my_new_module:8.x-1.x +``` + +In this case, the new branch will be `8.x-1.x`. + +Here is a screenshot of example module that I’ve split and pushed to GitLab. +Notice that there are multiple commits in the history, and each still attributed +to it’s original author. + +![Screenshot of a split project repo on GitLab](/images/blog/subtree-split-drupal-module.png) + +Also, as this is standard Git functionality, you can follow the same process to +extract PHP libraries, Symfony bundles, WordPress plugins or anything else. + +[0]: https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt +[1]: + https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt#L101-L108 +[2]: {{site.companies.drupal_association.url}} +[3]: https://getcomposer.org diff --git a/source/_posts/streaming-spabby-gary-hockin-about-drupal.md b/source/_posts/streaming-spabby-gary-hockin-about-drupal.md new file mode 100644 index 00000000..d536b76d --- /dev/null +++ b/source/_posts/streaming-spabby-gary-hockin-about-drupal.md @@ -0,0 +1,22 @@ +--- +title: Streaming with Spabby (Gary Hockin) about Drupal +excerpt: I recently joined my friend Gary on his stream to discuss Drupal. +tags: + - drupal + - php + - drupal-9 + - streaming +date: 2020-07-30 +--- + +I recently joined my friend and fellow [PHP South Wales](https://phpsouthwales.uk) regular [Gary Hockin](https://twitter.com/GeeH "Gary on Twitter") (aka GeeH, aka Spabby) on his stream to discuss one of my favourite topics, Drupal. + +I've noticed that a lot of Developers within the wider PHP community have maybe used or looked at an earlier version of Drupal, like 4, 5 or 6, but not a more recent version, so this seemed like a good opportunity to discuss and demo some of the modern features and improvements in Drupal to Gary's mostly PHP focussed audience. + +You can currently [view the video on Gary's Twitch page](https://www.twitch.tv/videos/689269586), or I've embedded it below. + +We touched on the topic of decoupled Drupal, and we're planning a follow-up stream where we pair program and set up Drupal together with a front-end React application, which would be great fun! + +
+ +
diff --git a/source/_posts/style-drupal-6s-taxonomy-lists-php-css-and-jquery.md b/source/_posts/style-drupal-6s-taxonomy-lists-php-css-and-jquery.md new file mode 100644 index 00000000..783df001 --- /dev/null +++ b/source/_posts/style-drupal-6s-taxonomy-lists-php-css-and-jquery.md @@ -0,0 +1,75 @@ +--- +title: Style Drupal 6's Taxonomy Lists with PHP, CSS and jQuery +date: 2010-04-05 +excerpt: Getting started with Drupal theming by styling Drupal’s taxonomy lists. +tags: + - drupal-6 + - drupal-planet + - drupal-theming + - taxonomy +--- + +Whilst developing this, and other Drupal websites for clients, I decided that I +wanted to categorise content using the taxonomy system. However, I wasn't happy +with the way that Drupal displayed the terms lists by default, and I started +comparing this to other websites that I look at. + +To start with, I wanted to have something that described what the list was +displaying - like in the second example above. I wanted to have the words +'Posted in' displayed before the list of terms. To do this, I had to edit the +node template file that exists within my theme folder (sites/all/themes). As I +only wanted this change to affect my Blog posts, the file that I needed to +change is **node-blog.tpl.php** + +I scrolled down until I found the piece of code that displayed the terms list: + +```php + +
+ +
+ +``` + +Adding `print t(' Posted in ')` will print the words 'Posted in' before +outputing the terms. + +I then added some CSS to re-size the spacing between the items, and then add the +commas between them to seperate them: + +```css +.terms ul.links li { + margin-right: 1px; + padding: 0; +} + +.terms ul.links li:after { + content: ","; +} + +.terms ul.links li.last:after { + content: "."; +} +``` + +I created a file named **script.js** in my theme folder with the following code +in it. After clearing Drupal's caches, this file is automatically recognised by +Drupal 6. + +```js +if (Drupal.jsEnabled) { + $(document).ready(function() { + $('.terms ul.links li.last').prev().addClass('test'); + }) +} +``` + +This code finds the last item in the list, uses **.prev** to select the one +before it, and then uses **.addClass** to assign it the HTML class of "test". We +can then use this class to target it with specific CSS. + +```css +.terms ul.links li.test:after { + content: " and"; +} +``` diff --git a/source/_posts/survey-results-my-drupalcon-europe-session-test-driven-drupal.md b/source/_posts/survey-results-my-drupalcon-europe-session-test-driven-drupal.md new file mode 100644 index 00000000..5f4e7eba --- /dev/null +++ b/source/_posts/survey-results-my-drupalcon-europe-session-test-driven-drupal.md @@ -0,0 +1,96 @@ +--- +title: Survey results from my DrupalCon Europe session (Test-Driven Drupal) +excerpt: Here are the results from the session survey for my DrupalCon session (Test-Driven Drupal) on Drupal automated testing and test-driven development. +tags: + - drupalcon + - speaking +date: 2021-01-22 +--- + +In December [I gave a talk at DrupalCon Europe](/blog/test-driven-drupal-presentation-drupalcon-europe) on automated testing and test-driven development in Drupal. At the end of each session, the attendees were shown a survey to complete and the results have just been released to the speakers. + +Here are the results from my session, and I've included the screenshot of the graphs at the bottom of this post. I'd like to thank everyone who attended the session live, and those who left valuable feedback afterward. + +If you want to see the slides and video for that session, click the link above to see the embedded slides and video. + +## Survey results + +Attendance: 134 + +### Did the session description accurately represent the content presented? + +* Yes - 96.8% +* No - 3.2% + +Total survey responses: 62 + +### Overall, how would you rate this session? + +* 5 - 44.8% +* 4 - 29.3% +* 3 - 19% +* 2 - 6.9% +* 1 - 0% + +Total survey responses: 58 + +### How would you rate the speaker(s)'s mastery of this topic? + +* Excellent - 64.4% +* Very good - 24.4% +* Good - 11.1% +* Fair - 0% +* Poor - 0% + +Total survey responses: 45 + +### How would you rate the speaker(s)'s presentation skills? + +* Excellent - 46.8% +* Very good - 31.9% +* Good - 10.6% +* Fair - 8.5% +* Poor - 2.1% + +Total survey responses: 47 + +### How would you rate the speaker(s)’s slides and other session materials? + +* Excellent - 47.8% +* Very good - 30.4% +* Good - 15.2% +* Fair - 6.5% +* Poor - 0% + +Total survey responses: 46 + +### What changes could the speaker(s) have made for you to give it a higher rating? + +* A little more insights (e.g. on test environment setup) +* Everything was perfect! Thank you :) +* He ist to fast ;) +* Just felt the end examples were rushed through slightly compared to the introduction at the start. +* Less examples to more focus. +* Nothing, was excellent +* Not to shy and interact afterwards +* Slower - too much content in too little time +* Speak a little slower, especially when going through the example code +* Yes + +### What did the speaker(s) do really well? + +* Broken down the steps into real clear examples +* Clear, concise slides, minimal code (Which can be hard to read) +* CodeBlocks +* Covers all relevant topics. +* End to end examples without just being a high level overview. +* Examples +* Good examples +* Good preparation, Good speed +* Good structured walkthrough +* Great knowledge +* Introduce the idea of TDD +* Yes +* You explained your workflow very clearly. You have a skill for making tricky concepts very clear. Thanks for a great talk. + + diff --git a/source/_posts/test-driven-ansible-role-development-molecule.md b/source/_posts/test-driven-ansible-role-development-molecule.md new file mode 100644 index 00000000..9c78b5d3 --- /dev/null +++ b/source/_posts/test-driven-ansible-role-development-molecule.md @@ -0,0 +1,39 @@ +--- +title: Test-Driven Ansible Role Development with Molecule +date: 2019-06-02 +excerpt: Some resources that I found for testing Ansible roles with a tool called Molecule. +tags: + - ansible + - molecule + - testing + - video +--- + +I used to maintain a number of [Ansible roles][roles], and I recently wrote one +for automatically generating `settings.php` files for Drupal projects that I use +for some client projects as part of the [Ansible and Ansistrano deployment +process][talk], as it can populate these files with credentials stored in +Ansible Vault. + +I uploaded an initial version of the role [onto GitHub][github], but haven’t yet +released it onto Ansible Galaxy. + +I’d seen in other people’s roles and read elsewhere about writing automated +tests for Ansible roles using a tool called [Molecule][molecule], and wanted to +write some tests for this role before publishing it onto Galaxy. + +I looked around for resources about Molecule, and found a [blog post by Jeff +Geerling][jeff-post], but also this YouTube video that I found very helpful. + +I’ve since been re-writing the role from scratch based on Molecule, and plan to +release an official version of it soon. + +{% include 'youtube-video' with { id: DAnMyBZ8-Qs } %} + +[github]: https://github.com/opdavies/ansible-role-drupal-settings +[jeff-post]: + https://www.jeffgeerling.com/blog/2018/testing-your-ansible-roles-molecule +[molecule]: https://molecule.readthedocs.io +[roles]: + https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html +[talk]: /talks/deploying-php-ansible-ansistrano diff --git a/source/_posts/test-driven-drupal-on-gitstore-leanpub.md b/source/_posts/test-driven-drupal-on-gitstore-leanpub.md new file mode 100644 index 00000000..db670b81 --- /dev/null +++ b/source/_posts/test-driven-drupal-on-gitstore-leanpub.md @@ -0,0 +1,37 @@ +--- +title: Test-Driven Drupal on Gitstore and Leanpub +excerpt: The work-in-progress codebase for the example application is now on Gitstore. +date: 2020-04-22 +tags: + - drupal + - drupal-8 + - drupal-association + - drupal-planet + - drupalcares + - testing + - test-driven-drupal +has_tweets: true +--- + +Some time ago, I announced that I was planning on writing a book on automated testing and test driven development with Drupal. I [created a landing page][landing page] and set up a mailing list, but I wasn't sure at that point what I was going to cover or create as part of the book. + + +{% include 'tweet' with { + class: 'my-6', + data_cards: true, + content: '

I'm going to write a book on automated testing in Drupal. Join the mailing list for updates, and I'm happy to take suggestions on what to cover. https://t.co/YXNpe6f8Ft #drupal

— Oliver Davies (@opdavies) May 15, 2018', +} %} + +Being a meetup and DrupalCamp conference organiser, after some thought I decided to build a website for an example conference, and that some of this code would then be included in the book as example content. This seemed to cover most of what I originally wanted, through features like a call for papers for potential speakers to propose sessions, allowing organisers to administer and moderate those proposals, automatically sending notification emails to submitters and displaying the accepted sessions. + +I've started building it with Drupal 8.8 and it is [now available on GitStore][gitstore] to purchase access to, including all future updates as I continue building the application - adding new features and upgrading to Drupal 9 once it is released. There are some other interesting things there too, such as using feature flags to enable or disable functionality, and using GitHub Actions to run the tests automatically. + +The book itself I've [added a page for on Leanpub][leanpub], and I'll be continuing to add content to it in parallel to building the example codebase. Once there is enough content, I will release the first draft for purchase. + +Any purchases that are made via Gitstore or Leanpub, an amount will be donated to the [Drupal Association][] and the [#DrupalCares campaign][drupalcares] to help sustain the Association during COVID-19. + +[drupal association]: https://www.drupal.org/association +[drupalcares]: https://www.drupal.org/association/drupal-cares-challenge +[gitstore]: https://enjoy.gitstore.app/repositories/opdavies/test-driven-drupal-conference-app +[landing page]: /test-driven-drupal +[leanpub]: https://leanpub.com/test-driven-drupal diff --git a/source/_posts/test-driven-drupal-presentation-drupalcon-europe.md b/source/_posts/test-driven-drupal-presentation-drupalcon-europe.md new file mode 100644 index 00000000..41393eaa --- /dev/null +++ b/source/_posts/test-driven-drupal-presentation-drupalcon-europe.md @@ -0,0 +1,22 @@ +--- +title: Test-Driven Drupal presentation from DrupalCon Europe +excerpt: Links to the video and slides from my automated testing session from DrupalCon Europe. +tags: + - drupal + - drupal-8 + - drupalcon + - speaking +date: 2021-01-12 +--- + +Today, the sessions from DrupalCon Europe were posted on the [Drupal Association YouTube channel](https://www.youtube.com/playlist?list=PLpeDXSh4nHjTP7vRC6LCak9adK2yp1P5S), including my session on automated testing and test-driven development in Drupal 8 (and 9): + +Here is the video of my presentation: + +
+ +
+ +Here is an embedded version of the slides, which I've updated since the talk: + + diff --git a/source/_posts/testing-tailwind-css-plugins-jest.md b/source/_posts/testing-tailwind-css-plugins-jest.md new file mode 100644 index 00000000..d22568af --- /dev/null +++ b/source/_posts/testing-tailwind-css-plugins-jest.md @@ -0,0 +1,284 @@ +--- +title: Testing Tailwind CSS plugins with Jest +date: 2019-04-29 +excerpt: How to write tests for Tailwind CSS plugins using Jest. +tags: + - javascript + - jest + - tailwind-css + - testing +promoted: true +--- + +
+**Note:** The content of this post is based on tests seen in Adam Wathan’s ["Working on Tailwind 1.0" video][working-on-tailwind-video], the Jest documentation website, and existing tests for other Tailwind plugins that I’ve used such as [Tailwind CSS Interaction Variants][tailwindcss-interaction-variants]. +
+ +## Preface + +In Tailwind 0.x, there was a `list-reset` utility that reset the list style and +padding on a HTML list, though it was removed prior to 1.0 and moved into +Tailwind’s base styles and applied by default. + +However, on a few projects I use Tailwind in addition to either existing custom +styling or another CSS framework, and don’t use `@tailwind base` (formerly +`@tailwind preflight`) so don’t get the base styles. + +Whilst I could re-create this by replacing it with two other classes +(`list-none` and `p-0`), I decided to write [my own Tailwind CSS plugin][repo] +to re-add the `list-reset` class. This way I could keep backwards compatibility +in my projects and only need to add one class in other future instances. + +In this post, I’ll use this as an example to show how to write tests for +Tailwind CSS plugins with a JavaScript testing framework called [Jest][jest]. + +More information about plugins for Tailwind CSS themselves can be found on the +[Tailwind website][tailwind-docs-plugins]. + +## Add dependencies + +To start, we need to include `jest` as a dependency of the plugin, as well as +`jest-matcher-css` to perform assertions against the CSS that the plugin +generates. + +We also need to add `tailwindcss` and `postcss` so that we can use them within +the tests. + +``` +yarn add -D jest jest-matcher-css postcss tailwindcss@next +``` + +This could be done with `yarn add` or `npm install`. + +## Writing the first test + +In this plugin, the tests are going to be added into a new file called +`test.js`. This file is automatically loaded by Jest based on it’s [testRegex +setting][jest-testregex-setting]. + +This is the format for writing test methods: + +```js +test('a description of the test', () => { + // Perform tasks and write assertions +}); +``` + +The first test is to ensure that the correct CSS is generated from the plugin +using no options. + +We do this by generating the plugin’s CSS, and asserting that it matches the +expected CSS within the test. + +```js +test('it generates the list reset class', () => { + generatePluginCss().then(css => { + expect(css).toMatchCss(` + .list-reset { + list-style: none; + padding: 0 + } + `); + }); +}); +``` + +However, there are some additional steps needed to get this working. + +### Generating the plugin’s CSS + +Firstly, we need to import the plugin’s main `index.js` file, as well as PostCSS +and Tailwind. This is done at the beginning of the `test.js` file. + +```js +const plugin = require('./index.js'); +const postcss = require('postcss'); +const tailwindcss = require('tailwindcss'); +``` + +Now we need a way to generate the CSS so assertions can be written against it. + +In this case, I’ve created a function called `generatePluginCss` that accepts +some optional options, processes PostCSS and Tailwind, and returns the CSS. + +```js +const generatePluginCss = (options = {}) => { + return postcss(tailwindcss()) + .process('@tailwind utilities;', { + from: undefined, + }) + .then(result => result.css); +}; +``` + +Alternatively, to test the output of a component, `@tailwind utilities;` would +be replaced with `@tailwind components`. + +```js +.process('@tailwind components;', { + from: undefined +}) +``` + +Whilst `from: undefined` isn’t required, if it’s not included you will get this +message: + +> Without `from` option PostCSS could generate wrong source map and will not +> find Browserslist config. Set it to CSS file path or to `undefined` to prevent +> this warning. + +### Configuring Tailwind + +In order for the plugin to generate CSS, it needs to be enabled within the test, +and Tailwind’s core plugins need to be disabled so that we can assert against +just the output from the plugin. + +As of Tailwind 1.0.0-beta5, this can be done as follows: + +``` +tailwindcss({ + corePlugins: false, + plugins: [plugin(options)] +}) +``` + +In prior versions, each plugin in `corePlugins` needed to be set to `false` +separately. + +I did that using a `disableCorePlugins()` function and [lodash][lodash], using +the keys from `variants`: + +``` +const _ = require('lodash') + +// ... + +const disableCorePlugins = () => { + return _.mapValues(defaultConfig.variants, () => false) +} +``` + +### Enabling CSS matching + +In order to compare the generated and expected CSS, [the CSS matcher for +Jest][jest-css-matcher] needs to be required and added using +[expect.extend][jest-expect-extend]. + +```js +const cssMatcher = require('jest-matcher-css') + +... + +expect.extend({ + toMatchCss: cssMatcher +}) +``` + +Without it, you’ll get an error message like _"TypeError: expect(...).toMatchCss +is not a function"_ when running the tests. + +## The next test: testing variants + +To test variants we can specify the required variant names within as options to +`generatePluginCss`. + +For example, this is how to enable `hover` and `focus` variants. + +```js +generatePluginCss({ variants: ['hover', 'focus'] }); +``` + +Now we can add another test that generates the variant classes too, to ensure +that also works as expected. + +```js +test('it generates the list reset class with variants', () => { + generatePluginCss({ variants: ['hover', 'focus'] }).then(css => { + expect(css).toMatchCss(` + .list-reset { + list-style: none; + padding: 0 + } + + .hover\\:list-reset:hover { + list-style: none; + padding: 0 + } + + .focus\\:list-reset:focus { + list-style: none; + padding: 0 + } + `); + }); +}); +``` + +## Running tests locally + +Now that we have tests, we need to be able to run them. + +With Jest included as a dependency, we can update the `test` script within +`package.json` to execute it rather than returning a stub message. + +```diff +- "test": "echo \"Error: no test specified\" && exit 1" ++ "test": "jest" +``` + +This means that as well as running the `jest` command directly to run the tests, +we can also run `npm test` or `yarn test`. + +After running the tests, Jest will display a summary of the results: + +![A screenshot of the Jest output after running the tests, showing 1 passed test suite and 2 passed tests, as well as the test run time.](/images/blog/testing-tailwindcss-plugins/running-tests.png) + +## Running tests automatically with Travis CI + +As well as running the tests locally, they can also be run automatically via +services like [Travis CI][travis] when a new pull request is submitted or each +time new commits are pushed. + +This is done by adding a `.travis-ci.yml` file to the repository, like this one +which is based on the [JavaScript and Node.js example][travis-nodejs-example]: + +```yaml +language: node_js + +node_js: + - '8' + +cache: + directories: + - node_modules + +before_install: + - npm update + +install: + - npm install + +script: + - npm test +``` + +With this in place, the project can now be enabled on the Travis website, and +the tests will be run automatically. + +For this plugin, you can see the results at +. + +[jest-css-matcher]: https://www.npmjs.com/package/jest-matcher-css +[jest-expect-extend]: https://jestjs.io/docs/en/expect#expectextendmatchers +[jest-testregex-setting]: + https://jestjs.io/docs/en/configuration#testregex-string-array-string +[jest]: https://jestjs.io +[lodash]: https://lodash.com +[repo]: https://github.com/opdavies/tailwindcss-list-reset +[tailwind-docs-plugins]: https://tailwindcss.com/docs/plugins +[tailwindcss-interaction-variants]: + https://www.npmjs.com/package/tailwindcss-interaction-variants +[travis-nodejs-example]: + https://docs.travis-ci.com/user/languages/javascript-with-nodejs +[travis]: https://travis-ci.org +[working-on-tailwind-video]: https://www.youtube.com/watch?v=SkTKN38wSEM diff --git a/source/_posts/thanks.md b/source/_posts/thanks.md new file mode 100644 index 00000000..ac7ce5fe --- /dev/null +++ b/source/_posts/thanks.md @@ -0,0 +1,14 @@ +--- +title: Thanks +date: 2014-05-06 +excerpt: Thanks everyone or their comments about my move to the Drupal Association. +tags: + - drupal + - drupal-association + - personal +--- + +This is just a quick post to thank everyone for their comments and +congratulations after my previous post about +[joining the Drupal Association](/blog/drupal-association/). I’m looking forward +to my first day in the job tomorrow. diff --git a/source/_posts/turning-drupal-module-into-feature.md b/source/_posts/turning-drupal-module-into-feature.md new file mode 100644 index 00000000..b34da9b4 --- /dev/null +++ b/source/_posts/turning-drupal-module-into-feature.md @@ -0,0 +1,35 @@ +--- +title: Turning Your Custom Drupal Module into a Feature +date: 2017-05-20 +excerpt: How to turn a custom Drupal module into a Feature. +tags: + - drupal + - drupal-7 + - drupal-planet + - features +--- + +Yesterday I was fixing a bug in an inherited Drupal 7 custom module, and I +decided that I was going to add some tests to ensure that the bug was fixed and +doesn’t get accidentially re-introduced in the future. The test though required +me to have a particular content type and fields which are specific to this site, +so weren’t present within the standard installation profile used to run tests. + +I decided to convert the custom module into a [Feature][0] so that the content +type and it’s fields could be added to it, and therefore present on the testing +site once the module is installed. + +To do this, I needed to expose the module to the Features API. + +All that’s needed is to add this line to the `mymodule.info` file: + +```ini +features[features_api][] = api:2 +``` + +After clearing the cache, the module is now visible in the Features list - and +ready to have the appropriate configuration added to it. + +!['The features list showing the custom module'](/images/blog/custom-module-as-a-feature.png) + +[0]: https://www.drupal.org/project/features diff --git a/source/_posts/tweets-drupalcamp-london.md b/source/_posts/tweets-drupalcamp-london.md new file mode 100644 index 00000000..13506a2b --- /dev/null +++ b/source/_posts/tweets-drupalcamp-london.md @@ -0,0 +1,69 @@ +--- +title: Tweets from DrupalCamp London +date: 2018-03-04 +excerpt: I wasn’t able to make it to DrupalCamp London, but here are some of the tweets that I saw. +tags: + - drupal + - drupalcamp + - drupalcamp-london +has_tweets: true +--- + +In the end, I wasn’t able to make it to DrupalCamp London because of the heavy +snow that’s hit the UK over the last few days. I did though keep a close eye on +Twitter and still had good conversations with some of the attendees, so it did +feel that in some ways I was still part of the conference. + +Thanks to [@ChandeepKhosa](https://twitter.com/ChandeepKhosa), +[@OrangePunchUK](https://twitter.com/OrangePunchUK), +[@hussainweb](https://twitter.com/hussainweb), +[@littlepixiez](https://twitter.com/littlepixiez), +[@cferthorney](https://twitter.com/cferthorney) and others for taking the time +to tweet whilst enjoying the event. + +Here are some of my favourites that I saw, and no snow next year, please! + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/source/_posts/uis-ive-rebuilt-tailwind-css.md b/source/_posts/uis-ive-rebuilt-tailwind-css.md new file mode 100644 index 00000000..044ab8d4 --- /dev/null +++ b/source/_posts/uis-ive-rebuilt-tailwind-css.md @@ -0,0 +1,22 @@ +--- +title: UIs that I've Rebuilt with Tailwind CSS +excerpt: A collection of all of the UIs that I've rebuilt using Tailwind CSS for talk demos etc. +tags: + - css + - tailwind-css +date: 2020-11-02 +--- + +Like Adam Wathan and other Tailwind CSS users, I've rebuilt a number of existing websites and user interfaces with [Tailwind CSS](https://tailwindcss.com), either for practice, to try out some new features, or for a demo for a talk where I like to have a relevant example for that audience. + +I thought that I'd list them all here, and keep the list up to date for future reference. Most of them are [tagged on GitHub](/tailwind-repos), though I have been using [Tailwind Play](https://play.tailwindcss.com) for the newest ones. + +Here is the list (last updated in November 2020): + +- [Bartik](https://rebuilding-bartik.oliverdavies.uk) (Drupal's default theme), built with Vue.js. I've also made a version using Alpine JS. +- [Acquia's hosting dashboard](https://rebuilding-acquia.oliverdavies.uk), built with Vue.js. +- [The WordPress 2019 theme](https://wp-tailwind.oliverdavies.uk), built for WordCamp Bristol 2019. +- [Symfony.com website](http://rebuilding-symfony.oliverdavies.uk), built for Leeds PHP meetup. +- [Bristol JS website](https://rebuilding-bristol-js.oliverdavies.uk), built with Vue.js for Bristol JS meetup. +- [Platform.sh's hosting dashboard](https://rebuilding-platformsh.oliverdavies.uk) - in progress. +- [Pantheon's hosting dashboard](/rebuilding-pantheon) - in progress. diff --git a/source/_posts/updating-features-adding-components-using-drush.md b/source/_posts/updating-features-adding-components-using-drush.md new file mode 100644 index 00000000..144da7e7 --- /dev/null +++ b/source/_posts/updating-features-adding-components-using-drush.md @@ -0,0 +1,74 @@ +--- +title: Updating Features and Adding Components Using Drush +date: 2014-10-21 +excerpt: How to update features on the command line using Drush. +tags: + - drupal + - drupal-planet + - drush + - features +--- + +If you use the [Features module](http://drupal.org/project/features) to manage +your Drupal configuration, it can be time consuming to update features through +the UI, especially if you are working on a remote server and need to keep +downloading and uploading files. + +If you re-create a feature through the UI, you'll be prompted to download a new +archive of the feature in its entirety onto your local computer. You could +either commit this into a local repository and then pull it remotely, or use a +tool such as SCP to upload the archive onto the server and commit it from there. +You can simplify this process by using [Drush](http://drush.org). + +## Finding Components + +To search for a component, use the `drush features-components` command. This +will display a list of all components on the site. As we're only interested in +components that haven't been exported yet, add the `--not-exported` option to +filter the results. + +To filter further, you can also use the `grep` command to filter the results. +For example, `drush features-components --not-exported field_base | grep foo`, +would only return non-exported field bases containing the word "foo". + +The result is a source and a component, separated by a colon. For example, +`field_base:field_foo`. + +## Exporting the Feature + +Once you have a list of the components that you need to add, you can export the +feature. This is done using the `drush features-export` command, along with the +feature name and the component names. + +For example: + +```bash +$ drush features-export -y myfeature field_base:field_foo field_instance:user-field_foo +``` + +In this example, the base for field_boo and it's instance on the user object is +being added to the "myfeature" feature. + +If you are updating an existing feature, you'll get a message informing you that +the module already exists and asking if you want to continue. This is fine, and +is automatically accepted by including `-y` within the command. If a feature +with the specified name doesn't exist, it will be created. + +If you're creating a new feature, you can define where the feature will be +created using the `--destination` option. + +Once complete, you will see a confirmation message. + +> Created module: my feature in sites/default/modules/custom/features/myfeature + +## The Result + +Once finished, the feature is updated in it's original location, so there's no +download of the feature and then needing to re-upload it. You can add and commit +your changes into Git or continue with your standard workflow straight away. + +## Useful Links + +- [The Features project page on Drupal.org](http://www.drupal.org/project/features) +- [The "drush features-components" command](http://www.drushcommands.com/drush-6x/features/features-components) +- [The "drush features-export" command](http://www.drushcommands.com/drush-6x/features/features-export) diff --git a/source/_posts/updating-forked-github-repos.md b/source/_posts/updating-forked-github-repos.md new file mode 100644 index 00000000..e4602b03 --- /dev/null +++ b/source/_posts/updating-forked-github-repos.md @@ -0,0 +1,121 @@ +--- +title: Updating Forked Repositories on GitHub +date: 2015-06-18 +excerpt: I just had to update a repo that I forked on GitHub. This is how I did it. Did I do it the correct way? +tags: + - git + - github + - phpstorm + - sculpin +--- + +I just had to update a repo that I forked on GitHub. This is how I did it. Did I +do it the correct way? + +## Sculpin + +People may or may not know, but this site runs on +[Sculpin](https://sculpin.io/), a PHP based static site generator (this may be +the first time that I've mentioned it on this site). The source code is hosted +on [GitHub](https://github.com/opdavies/oliverdavies.uk), and I've listed the +site on the [Community page](https://sculpin.io/community/) on the Sculpin +website. + +To get it there, I forked the +[main sculpin.io repository](https://github.com/sculpin/sculpin.io) so that I +had [my own copy](https://github.com/opdavies/sculpin.io), created a branch, +made my additions and submitted a pull request. Easy enough! + +## New Domain + +In the last week or so, I've changed this site URL from .co.uk to just .uk, and +also updated the GitHub repo URL to match, so I wanted to update the Community +page to use the correct URL. + +There had been commits to the main repo since my pull request was merged, I +didn't want to delete my repo and fork again, and making any changes against and +old codebase isn't best practice, so I wanted to merge the latest changes into +my forked repo before I did anything else - just to check that I didn't break +anything! + +## Updating my Local Repo + +I had a quick look for a _Update my fork_ button or something, but couldn't see +one to I added the main repository as an additional remote called `upstream` and +fetched the changes. + +```bash +$ git remote add upstream https://github.com/sculpin/sculpin.io.git + +$ git fetch upstream +remote: Counting objects: 33, done. +remote: Total 33 (delta 6), reused 6 (delta 6), pack-reused 27 +Unpacking objects: 100% (33/33), done. +From https://github.com/sculpin/sculpin.io +* [new branch] master -> upstream/master +* [new branch] pr/4 -> upstream/pr/4 +``` + +Now my local site knows about the upstream repo, and I could rebase the changes +(`git pull upstream master` should have worked too) and push them back to +origin. + +```bash +$ git rebase upstream/master +First, rewinding head to replay your work on top of it... +... +Fast-forwarded master to upstream/master. + +$ git push origin master +``` + +This seems to have worked OK - the commits are still authored by the correct +people and at the correct date and time - and I went ahead and created a new +feature branch and pull request based on that master branch. + +{% include 'figure' with { + image: { + src: '/images/blog/forked-github-repo-commits.png', + alt: 'The commits on my master branch after rebasing', + }, + caption: 'The commits on my forked master branch after rebasing and pushing. All good!', +} %} + +{% include 'figure' with { + image: { + src: '/images/blog/my-commit-to-the-rebased-branch.png', + alt: 'The new feature branch with my additional commit', + }, + caption: 'The new feature branch with the new commit.', +} %} + +## Is There a Better Way? + +Did I miss something? Is there a recommended and/or better way to update your +forked repos, maybe through the UI? Please +send +me a tweet with any comments. + +## Up + +**December 2015:** I’ve found that PhpStorm has an option available to rebase a +fork from within the IDE. This is within the _VCS_ > _Git_ menu. + +I believe that it will use an existing "upstream" remote if it exists, otherwise +it will add one automatically for you, linking to the repository that you forked +from. + +Once you’ve completed the rebase, you can then push your updated branch either +from the terminal, or using the _Push_ command from the same menu. + +![Rebasing a forked repository in PhpStorm using the VCS menu.](/images/blog/github-fork-rebase-phpstorm.png) + +It would be great to see something similar added to +[hub](https://hub.github.com) too (I’ve created +[an issue](https://github.com/github/hub/issues/1047))! + +## Resources + +- [PhpStorm - Advanced GitHub Integration: Rebase My GitHub Fork (blog post)](http://blog.jetbrains.com/idea/2011/02/advanced-github-integration-rebase-my-github-fork/) +- [Rebasing a GitHub fork inside PhpStorm (video)](https://www.youtube.com/watch?v=Twy-dhVgN4k) +- [hub](https://hub.github.com) - makes Git better with GitHub diff --git a/source/_posts/updating-override-node-options-tests.md b/source/_posts/updating-override-node-options-tests.md new file mode 100644 index 00000000..dbf62193 --- /dev/null +++ b/source/_posts/updating-override-node-options-tests.md @@ -0,0 +1,239 @@ +--- +title: Updating Override Node Options Tests +date: 2017-05-05 +excerpt: ~ +tags: + - drupal + - drupal-modules + - drupal-planet + - testing +draft: true +--- + +Recently, I reviewed [a patch][1] in the [Override Node Options][2] module issue +queue. For those not familiar with it, the module adds extra permissions for +node options like "authored by" and "published on" which are normally only +available to users with the `administer nodes` permission. What the patch does +is to optionally add another set of permissions that enable options for all +content types - e.g. "override published option for all node types", in addition +to or instead of the content type specific ones. + +It was quite an old issue and the latest patch needed to be re-rolled due to +merge conflicts, but the existing tests still passed. Though as no new tests +were added for the new functionality, these needed to be added before I +committed it. + +## Reviewing the Existing Tests + +The first thing to do was to run the existing tests and check that they still +passed. I do this on the command line by typing +`php scripts/run-tests.sh --class OverrideNodeOptionsTestCase`. + +``` +Drupal test run +--------------- + +Tests to be run: + - Override node options (OverrideNodeOptionsTestCase) + +Test run started: + Saturday, April 29, 2017 - 14:44 + +Test summary +------------ + +Override node options 142 passes, 0 fails, 0 exceptions, and 38 debug messages + +Test run duration: 32 sec +``` + +After confirming that the existing tests still passed, I reviewed them to see +what could be re-used. + +This is one of the original tests: + +```php +/** + * Test the 'Authoring information' fieldset. + */ +protected function testNodeOptions() { + $this->adminUser = $this->drupalCreateUser(array( + 'create page content', + 'edit any page content', + 'override page published option', + 'override page promote to front page option', + 'override page sticky option', + 'override page comment setting option', + )); + $this->drupalLogin($this->adminUser); + + $fields = array( + 'status' => (bool) !$this->node->status, + 'promote' => (bool) !$this->node->promote, + 'sticky' => (bool) !$this->node->sticky, + 'comment' => COMMENT_NODE_OPEN, + ); + $this->drupalPost('node/' . $this->node->nid . '/edit', $fields, t('Save')); + $this->assertNodeFieldsUpdated($this->node, $fields); + + $this->drupalLogin($this->normalUser); + $this->assertNodeFieldsNoAccess($this->node, array_keys($fields)); +} +``` + +The first part of the test is creating and logging in a user with some content +type specific override permissions (`$this->adminUser`), and then testing that +the fields were updated when the node is saved. The second part is testing that +the fields are not visible for a normal user without the extra permissions +(`$this->normalUser`), which is created in the `setUp()` class' method. + +To test the new "all types" permissions, I created another user to test against +called `$generalUser` and run the first part of the tests in a loop. + +## Beginning to Refactor the Tests + +With the tests passing, I was able to start refactoring. + +```php +// Create a new user with content type specific permissions. +$specificUser = $this->drupalCreateUser(array( + 'create page content', + 'edit any page content', + 'override page published option', + 'override page promote to front page option', + 'override page sticky option', + 'override page comment setting option', +)); + +foreach (array($specificUser) as $account) { + $this->drupalLogin($account); + + // Test all the things. + ... +} +``` + +I started with a small change, renaming `$this->adminUser` to `$specificUser` to +make it clearer what permissions it had, and moving the tests into a loop so +that the tests can be repeated for both users. + +After that change, I ran the tests again to check that everything still worked. + +## Adding Failing Tests + +The next step is to start testing the new permissions. + +```php +... + +$generalUser = $this->drupalCreateUser(array()); + +foreach (array($specificUser, $generalUser) as $account) { + $this->drupalLogin($account); + + // Test all the things. +} +``` + +I added a new `$generalUser` to test the general permissions and added to the +loop, but in order to see the tests failing intially I assigned it no +permissions. When running the tests again, 6 tests have failed. + +``` +Test summary +------------ + +Override node options 183 passes, 6 fails, 0 exceptions, and 49 debug messages + +Test run duration: 28 sec +``` + +Then it was a case of re-adding more permissions to the user and seeing the +number of failures decrease, confirming that the functionality was working +correctly. + +TODO: Add another example. + +## Gotchas + +There was a bug that I found where a permission was added, but wasn't used +within the implementation code. After initially expecting the test to pass after +adding the permission to `$generalUser` and the test still failed, I noticed +that the + +This was fixed by adding the extra code into `override_node_options.module`. + +```diff +- $form['comment_settings']['#access'] |= user_access('override ' . $node->type . ' comment setting option'); ++ $form['comment_settings']['#access'] |= user_access('override ' . $node->type . ' comment setting option') || user_access('override all comment setting option'); +``` + +The other issue that I found was within `testNodeRevisions`. +`assertNodeFieldsUpdated()` was failing after being put in a loop as the `vid` +was not the same as what was expected. + +Note: You can get more verbose output from `run-tests.sh` by adding the +`--verbose` option. + +> Node vid was updated to '3', expected 2. + +```diff +- $fields = array( +- 'revision' => TRUE, +- ); +- $this->drupalPost('node/' . $this->node->nid . '/edit', $fields, t('Save')); +- $this->assertNodeFieldsUpdated($this->node, array('vid' => $this->node->vid + 1)); ++ $generalUser = $this->drupalCreateUser(array( ++ 'create page content', ++ 'edit any page content', ++ 'override all revision option', ++ )); ++ ++ foreach (array($specificUser, $generalUser) as $account) { ++ $this->drupalLogin($account); ++ ++ // Ensure that we have the latest node data. ++ $node = node_load($this->node->nid, NULL, TRUE); ++ ++ $fields = array( ++ 'revision' => TRUE, ++ ); ++ $this->drupalPost('node/' . $node->nid . '/edit', $fields, t('Save')); ++ $this->assertNodeFieldsUpdated($node, array('vid' => $node->vid + 1)); ++ } +``` + +The crucial part of this change was the addition of +`$node = node_load($this->node->nid, NULL, TRUE);` to ensure that the latest +version of the node was loaded during each loop. + +## Conclusion + +- Ensure that the existing tests were passing before starting to refactor. +- Start with small changes and continue to run the tests to ensure that nothing + has broken. +- After the first change, I committed it as `WIP: Refactoring tests`, and used + `git commit --amend --no-edit` to amend that commit each time I had refactored + another test. After the last refactor, I updated the commit message. +- It’s important to see tests failing before making them pass. This was achieved + by initially assigning no permissions to `$generalUser` so that the fails + failed and then added permissions and re-run the tests to ensure that the + failure count decreased with each new permission. + +With the refactoring complete, the number of passing tests increased from 142 +to 213. + +``` +Override node options 213 passes, 0 fails, 0 exceptions, and 60 debug messages + +Test run duration: 25 sec +``` + + + +[Here][3] are my full changes from the previous patch, where I added the new +tests as well as some small refactors. + +[1]: https://www.drupal.org/node/974730 +[2]: https://www.drupal.org/project/override_node_options +[3]: https://www.drupal.org/files/issues/interdiff_25712.txt diff --git a/source/_posts/upgrading-dransible-project-drupal-9.md b/source/_posts/upgrading-dransible-project-drupal-9.md new file mode 100644 index 00000000..33e7d352 --- /dev/null +++ b/source/_posts/upgrading-dransible-project-drupal-9.md @@ -0,0 +1,51 @@ +--- +title: Upgrading the Dransible project to Drupal 9 +excerpt: How I recently upgraded the Dransible example project from Drupal 8.8 to 9.0. +tags: + - composer + - dransible + - drupal + - drupal-9 + - drupal-planet + - php +date: 2020-09-05 +--- + +This week I gave [a new talk on upgrading to Drupal 9](/talks/upgrading-your-site-drupal-9) for the Drupal NYC meetup. Whilst preparing for that, I decided to upgrade my [Dransible example project](https://github.com/opdavies/dransible) that I use for my [Ansible and Ansistrano talk](/talks/deploying-php-ansible-ansistrano) to Drupal 9 and document the process. + +Whilst the steps taken are in the slides for that talk, here is the full list of steps that I took including the Composer commands. + +## Updating from Drupal 8.8 to 8.9 { #updating-from-drupal-88-to-89 } + +To begin with, let's update to the latest version of Drupal 8 so that we can do some testing and see all of the latest deprecation notices before moving to Drupal 9. + +1. Remove Drush temporarily using `composer remove drush/drush` as it will cause us being stuck on Drupal 8.9.0-beta2 rather than a newer, stable 8.9 version. +1. Update `^8.8` to `^8.9` in composer.json for `drupal/core-recommended`, `drupal/core-dev` and `drupal/core-composer-scaffold`, and run `composer update drupal/core-* --with-dependencies` to update core to 8.9.5. +1. Re-add Drush so that it's present for the deployment by running `composer require drush/drush:^9`. + +## Preparing for Drupal 9 {#preparing-drupal-9} + +1. Add the [Upgrade Status module](https://www.drupal.org/project/upgrade_status) by running `composer require drupal/upgrade_status`. +1. Upgrade to Drush 10 by running `composer require drush/drush:^10`. +1. Remove the [Config Installer module](https://www.drupal.org/project/config_installer) by running `composer remove drupal/config_installer`. This is no longer needed since Drupal 8.6, and there will be no Drupal 9 version. +1. Update the [Admin Toolbar module](https://www.drupal.org/project/admin_toolbar) to 2.3, a Drupal 9 compatible version, by running `composer update drupal/admin_toolbar`. + +As I'd previously updated the Simple Message custom module to be Drupal 9 compatible (adding the `core_version_requirement` key to the info.yml file, and removing usages of deprecated code), no changes needed to be made to that. + +## Upgrading to Drupal 9 {#upgrading-drupal-9} + +1. Update `^8.9` to `^9.0` for the core packages in composer.json, and run `composer update drupal/core-* --with-dependencies` to update to 9.0.5. +1. Re-add Drush by running `composer require drush/drush`. This will install Drush 10 by default. + +## Post upgrade {#post-upgrade} + +Although everything seemed to have updated OK locally, there were some errors when running a deployment to the Vagrant virtual machine that needed to be addressed, as well as some post-upgrade housekeeping steps to perform. + +1. Fix the deployment error by adding the [Symfony Configuration component](https://symfony.com/components/Config) as a dependency by running `composer require symfony/config:^4`. +1. Alias `Drupal\Core\Messenger\MessengerInterface` to `messenger` in `simple_message.services.yml` to fix the autowiring error. +1. Add `settings["config_sync_directory"]` to settings file variables (this will be added automatically in the next version of the [Drupal settings Ansible role](https://github.com/opdavies/ansible-role-drupal-settings)). +1. Remove the Upgrade Status module by running `composer remove drupal/upgrade_status`, as it's no longer needed. + +And that's it! The Dransible demo project is upgraded, and if you see my Ansible deployments talk in the future, the demo site will be running on Drupal 9. + +If you want to see the original pull request, it's at . diff --git a/source/_posts/use-authorized-keys-create-passwordless-ssh-connection.md b/source/_posts/use-authorized-keys-create-passwordless-ssh-connection.md new file mode 100644 index 00000000..eda31b02 --- /dev/null +++ b/source/_posts/use-authorized-keys-create-passwordless-ssh-connection.md @@ -0,0 +1,33 @@ +--- +title: How to use Authorized Keys to Create a Passwordless SSH Connection +date: 2012-02-01 +excerpt: How to generate a SSH key, and how to use to log in to a server using SSH without entering a password. +tags: + - linux + - ssh +--- + +If you're accessing Linux servers or automating tasks between servers, rather +than having to enter your user password every time, you can also use SSH public +key authentication. This is a simple process that involves creating a local key +and storing it within the _authorized_keys_ file on the remote server. + +1. Check if you already have a SSH key. `$ ssh-add -L` +1. If you don't have one, create one. `$ ssh-keygen` +1. Upload the key onto the server. Replace _myserver_ with the hostname or IP + address of your remote server. `$ ssh-copy-id myserver` + +If you're using Mac OS X and you don't have ssh-copy-id installed, download and +install [Homebrew](http://mxcl.github.com/homebrew 'Homebrew') and run the +`brew install ssh-copy-id` command. + +If successful, you should now see a message like: + +> Now try logging into the machine, with "ssh 'myserver'", and check in: +> +> ~/.ssh/authorized_keys +> +> to make sure we haven't added extra keys that you weren't expecting. + +Now the next time that you SSH onto the server, it should log you in without +prompting you for your password. diff --git a/source/_posts/use-regular-expressions-search-replace-coda-or-textmate.md b/source/_posts/use-regular-expressions-search-replace-coda-or-textmate.md new file mode 100644 index 00000000..eaacc8f3 --- /dev/null +++ b/source/_posts/use-regular-expressions-search-replace-coda-or-textmate.md @@ -0,0 +1,57 @@ +--- +title: Use Regular Expressions to Search and Replace in Coda or TextMate +date: 2010-11-04 +excerpt: How to perform searches using regular expressions. +tags: + - coda + - database + - regular-expression + - sequel-pro + - taxonomy + - textmate +--- + +As in +[the original post](/blog/add-taxonomy-term-multiple-nodes-using-sql/ 'Quickly adding a taxonomy term to multiple nodes using SQL'), +I'd generated a list of node ID values, and needed to add structure the SQL +update statment formatted in a certain way. However, I changed my inital query +slightly to out put the same nid value twice. + +```sql +SELECT nid, nid FROM node WHERE TYPE = 'blog' ORDER BY nid ASC; +``` + +Then, I could select all of the returned rows, copy the values, and paste them +into Coda: + +As before, I needed my SQL update statement to be in the following format: + +```sql +INSERT INTO term_node VALUE (nid, vid, tid), (nid2, vid2, tid); +``` + +As I mentioned previously, the nid and vid values are the same for each node, +and the tid will remain constant. In this case, the tid value that I needed to +use was '63'. + +So, using the 'Find and Replace' function within Coda, combined with +[regular expressions](http://en.wikipedia.org/wiki/Regular_expression) (regex), +I can easily format the values as needed. To begin with, I need to ensure that +the RegEx search option is enabled, and that I'm using the correct escape +character. + +The first thing that I wanted to do was add the seperating comma between the two +values. To do this, I perform a search for `\s*\t`. This searches for everything +that is whitespace AND is a tab value. I can then add the comma as the +replacement for each result. + +All 31 lines have been changed. + +Next, I can use `\n` to target the lines between the rows. I'll replace it with +the next comma, the number 63 (the tid value), the closing bracket, another +comma, re-add the line and add the opening bracket. + +The only two lines that aren't changed are the first and last, as they don't +have any line breaks following them. I can complete these lines manually. Now +all I need to do is add the beginning of the SQL update statement, then copy and +paste it into Sequel Pro. diff --git a/source/_posts/use-sass-and-compass-drupal-7-using-sassy.md b/source/_posts/use-sass-and-compass-drupal-7-using-sassy.md new file mode 100644 index 00000000..2ebae84f --- /dev/null +++ b/source/_posts/use-sass-and-compass-drupal-7-using-sassy.md @@ -0,0 +1,79 @@ +--- +title: How to use SASS and Compass in Drupal 7 using Sassy +date: 2012-12-06 +excerpt: Use PHPSass and the Sassy module to use Sass and Compass in your Drupal theme. +tags: + - compass + - css + - drupal + - drupal-7 + - drupal-planet + - less + - preprocessing + - sass +--- + +I've recently started using [SASS](http://sass-lang.com) rather than LESS to do +my CSS preprocessing - namely due to its integration with +[Compass](http://compass-style.org) and it's built-in CSS3 mixins. Here are +three modules that provide the ability to use SASS within Drupal. + +- [Sassy](http://drupal.org/project/sassy 'Sassy module on drupal.org') +- [Prepro](http://drupal.org/project/prepro 'Prepro module on drupal.org') +- [Libraries API](http://drupal.org/project/libraries 'Libraries API module on drupal.org') + +Alternatively, you could use a base theme like +[Sasson](http://drupal.org/project/sasson 'Sasson theme on drupal.org') that +includes a SASS compiler. + +## Download the PHPSass Library + +The first thing to do is download the PHPSass library from +[GitHub](https://github.com/richthegeek/phpsass 'PHPSass on GitHub'), as this is +a requirement of the Sassy module and we can't enable it without the library. +So, in a Terminal window: + +```bash +$ mkdir -p sites/all/libraries; +$ cd sites/all/libraries; +$ wget https://github.com/richthegeek/phpsass/archive/master.tar.gz; +$ tar zxf master.tar.gz; +$ rm master.tar.gz; +$ mv phpsass-master/ phpsass +``` + +Or, if you're using Drush Make files: + +```ini +libraries[phpsass][download][type] = "get" +libraries[phpsass][download][url] = "https://github.com/richthegeek/phpsass/archive/master.tar.gz" +``` + +The PHPSass library should now be located at `sites/all/libraries/phpsass`. + +## Download and enable the Drupal modules + +This is easy if you use [Drush](http://drupal.org/project/drush): + +```bash +$ drush dl libraries prepro sassy +$ drush en -y libraries prepro sassy sassy_compass +``` + +Otherwise, download the each module from it's respective project page and place +it within your `sites/all/modules` or `sites/all/modules/contrib` directory. + +## Configuring the Prepro module + +The Prepro module provides various settings that can be changed for each +preprocessor. Go to `admin/config/media/prepro` to configure the module as +required. + +Personally, in development, I'd set caching to 'uncached' and the error +reporting method to 'show on page'. In production, I'd change these to "cached" +and "watchdog" respectively. I'd also set the output style to "compressed", + +## Adding SASS files into your theme + +With this done, you can now add SASS and SCSS files by adding a line like +`stylesheets[all][] = css/base.scss` in your theme's .info file. diff --git a/source/_posts/useful-drupal-6-modules.md b/source/_posts/useful-drupal-6-modules.md new file mode 100644 index 00000000..1b482bd7 --- /dev/null +++ b/source/_posts/useful-drupal-6-modules.md @@ -0,0 +1,57 @@ +--- +title: 10 Useful Drupal 6 Modules +date: 2010-06-25 +excerpt: A list of 10 contributed modules that I currently use on each Drupal project. +tags: + - drupal + - drupal-6 + - drupal-modules + - drupal-planet +--- + +Aside from the obvious candidates such as Views, CCK etc, here are a list of 10 +contributed modules that I currently use on each Drupal project. + +So, in no particular order: + +- **[Admin](http://drupal.org/project/admin):**
The admin module provides UI + improvements to the standard Drupal admin interface. I've just upgraded to the + new [6.x-2.0-beta4](http://drupal.org/node/835870) version, and installed the + newly-required + [Rubik](http://code.developmentseed.org/rubik)/[Tao](http://code.developmentseed.org/tao) + themes. So far, so good! +- **[Better Permissions](http://drupal.org/project/better_perms)/[Filter Permissions](http://drupal.org/project/filter_perms): +
**Basic permissions is a basic module which enhances the Drupal + Permissions page to support collapsing and expanding permission rows. Filter + permissions provides filters at the top of the Permissions page for easier + management when your site has a large amount of roles and/or permissions. +- **[Better Formats](http://drupal.org/project/better_formats):
**Better + formats is a module to add more flexibility to Drupal's core input format + system. +- **[Clone module](http://drupal.org/project/node_clone):**
Allows users to + make a copy of an existing item of site content (a node) and then edit that + copy. +- **[Vertical Tabs](http://drupal.org/project/vertical_tabs):
**Integrated + into Drupal 7 core, this module adds vertical tabs to the node add and edit + forms. +- **[Context](http://drupal.org/project/context):
**Context allows you to + manage contextual conditions and reactions for different portions of your + site. You can think of each context as representing a "section" of your site. + For each context, you can choose the conditions that trigger this context to + be active and choose different aspects of Drupal that should react to this + active context. +- **[Node Picker](http://drupal.org/project/nodepicker):**
A rewrite of the + module [TinyMCE Node Picker](http://drupal.org/project/tinymce_node_picker). + Allows you to easily create links to internal nodes. +- **[Module Filter](http://drupal.org/project/module_filter):**
What this + module aims to accomplish is the ability to quickly find the module you are + looking for without having to rely on the browsers search feature which more + times than not shows you the module name in the 'Required by' or 'Depends on' + sections of the various modules or even some other location on the page like a + menu item. +- **[Zenophile](http://drupal.org/project/zenophile):**
Quickly create Zen + subthemes. +- **[Add Another](http://drupal.org/project/addanother):**
Add another + displays a message after a user creates a node, and/or displays an "Add + another" tab on nodes allowing them to make another node of the same type. You + can control what roles and node types see this feature. diff --git a/source/_posts/useful-vagrant-commands.md b/source/_posts/useful-vagrant-commands.md new file mode 100644 index 00000000..0e63a7e7 --- /dev/null +++ b/source/_posts/useful-vagrant-commands.md @@ -0,0 +1,24 @@ +--- +title: Useful Vagrant Commands +date: 2013-11-27 +excerpt: Here are the basic commands that you need to adminster a virtual machine using Vagrant. +tags: + - vagrant +--- + +[Vagrant](http://www.vagrantup.com 'About Vagrant') is a tool for managing +virtual machines within [VirtualBox](https://www.virtualbox.org) from the +command line. Here are some useful commands to know when using Vagrant. + +| Command | Description | +| :--------------------------- | :----------------------------------------------------------------------------------------------------------- | +| vagrant init {box} | Initialise a new VM in the current working directory. Specify a box name, or "base" will be used by default. | +| vagrant status | Shows the status of the Vagrant box(es) within the current working directory tree. | +| vagrant up (--provision) | Boots the Vagrant box. Including "–provision" also runs the "vagrant provision" command. | +| vagrant reload (--provision) | Reloads the Vagrant box. Including "--provision" also runs the "vagrant provision" command. | +| vagrant provision | Provision the Vagrant box using Puppet. | +| vagrant suspend | Suspend the Vagrant box. Use "vagrant up" to start the box again. | +| vagrant halt (-f) | Halt the Vagrant box. Use -f to forcefully shut down the box without prompting for confirmation. | +| vagrant destroy (-f) | Destroys a Vagrant box. Use -f to forcefully shut down the box without prompting for confirmation. | + +The full Vagrant documentation can be found at . diff --git a/source/_posts/using-feature-flags-in-drupal-development.md b/source/_posts/using-feature-flags-in-drupal-development.md new file mode 100644 index 00000000..b57ac762 --- /dev/null +++ b/source/_posts/using-feature-flags-in-drupal-development.md @@ -0,0 +1,13 @@ +--- +title: Using feature flags in Drupal development +excerpt: Different ways of using feature flags witin Drupal development +date: 2020-03-31 +tags: + - drupal + - drupal-7 + - drupal-8 + - php +draft: true +--- + +TODO. diff --git a/source/_posts/using-imagecache-and-imagecrop-my-portfolio.md b/source/_posts/using-imagecache-and-imagecrop-my-portfolio.md new file mode 100644 index 00000000..422901aa --- /dev/null +++ b/source/_posts/using-imagecache-and-imagecrop-my-portfolio.md @@ -0,0 +1,44 @@ +--- +title: Using ImageCache and ImageCrop for my Portfolio +date: 2010-04-28 +excerpt: How to create thumbnail images using the ImageCache and ImageCrop modules. +tags: + - drupal + - drupal-6 + - cck + - imagecache + - imagecrop + - imagefield +--- + +Whilst working on my own portfolio/testimonial website, I decided to have a +portfolio page displaying the name of each site and a thumbnail image. For this +Blog post, I'll be using a site called +[Popcorn Strips](http://popcornstrips.com) which I built for a friend earlier +this year as an example. + +I created a content type called 'Project' with a CCK ImageField called +'Screenshot'. I created a project called +[Popcorn Strips](http://popcornstrips.com), used the +[ScreenGrab](https://addons.mozilla.org/addon/1146) add-on for Mozilla Firefox +to take a screenshot of the website, and uploaded it to the project node. + +I created a View to display the published projects, and an ImageCache preset to +create the thumbnail image by scaling and cropping the image to a size of +200x100 pixels. + +Although, this automatically focused the crop on the centre of the image, +whereas I wanted to crop from the top and left of the image - showing the site's +logo and header. + +I installed the [ImageCrop](http://drupal.org/project/imagecrop) module, which +add a jQuery crop function to the standard ImageCache presents. I removed the +original Scale and Crop action and replaced it with a Scale action with a width +of 200px. + +I then added a new 'Javascript crop' action with the following settings: + +- Width: 200px +- Height: 100px +- xoffset: Left +- yoffset: Top diff --git a/source/_posts/using-laravel-collections-drupal.md b/source/_posts/using-laravel-collections-drupal.md new file mode 100644 index 00000000..e3345206 --- /dev/null +++ b/source/_posts/using-laravel-collections-drupal.md @@ -0,0 +1,71 @@ +--- +title: Examples of using Laravel Collections in Drupal +date: 2018-08-23 +excerpt: Some examples of using Laravel’s Illuminate Collections within Drupal projects. +tags: + - drupal + - drupal-7 + - drupal-8 + - drupal-planet + - laravel + - laravel-collections + - php +has_tweets: true +--- + +Since starting to work with Laravel as well as Drupal and Symfony, watching Adam +Wathan’s [Refactoring to Collections][0] course as well as [lessons on +Laracasts][6], I’ve become a fan of [Laravel’s Illuminate Collections][1] and +the object-orientated pipeline approach for interacting with PHP arrays. + +In fact I’ve given a talk on [using Collections outside Laravel][2] and have +written a [Collection class module][3] for Drupal 7. + +I’ve also tweeted several examples of code that I’ve written within Drupal that +use Collections, and I thought it would be good to collate them all here for +reference. + +Thanks again to [Tighten][4] for releasing and maintaining the +[tightenco/collect library][5] that makes it possible to pull in Collections via +Composer. + +
+ {% include 'tweet' with { + class: 'block mb-4 lg:w-1/2 lg:px-2 lg:mb-0', + data_cards: true, + content: '

Putting @laravelphp's Collection class to good use, cleaning up some of my @drupal 8 code. Thanks @TightenCo for the Collect library! pic.twitter.com/Bn1UfudGvp

— Oliver Davies (@opdavies) August 18, 2017', + } %} + + {% include 'tweet' with { + class: 'block mb-4 lg:w-1/2 lg:px-2 lg:mb-0', + data_cards: true, + content: '

Putting more @laravelphp Collections to work in my @drupal code today. 😁 pic.twitter.com/H8xDTT063X

— Oliver Davies (@opdavies) February 14, 2018', + } %} + + {% include 'tweet' with { + class: 'block mb-4 lg:w-1/2 lg:px-2 lg:mb-0', + data_cards: true, + content: '

I knew that you could specify a property like 'price' in Twig and it would also look for methods like 'getPrice()', but I didn't know (or had maybe forgotten) that @laravelphp Collections does it too.

This means that these two Collections return the same result.

Nice! 😎 pic.twitter.com/2g2IfThzdy

— Oliver Davies (@opdavies) June 20, 2018', + } %} + + {% include 'tweet' with { + class: 'block mb-4 lg:w-1/2 lg:px-2 lg:mb-0', + data_cards: true, + content: '

More @laravelphp Collection goodness, within my #Drupal8 project! pic.twitter.com/mWgpNbNIrh

— Oliver Davies (@opdavies) August 10, 2018', + } %} + + {% include 'tweet' with { + class: 'block mb-4 lg:w-1/2 lg:px-2 lg:mb-0', + data_cards: true, + content: '

Some more #Drupal 8 fun with Laravel Collections. Loading the tags for a post and generating a formatted string of tweetable hashtags. pic.twitter.com/GbyiRPzIRo

— Oliver Davies (@opdavies) August 23, 2018', + } %} + +
+ +[0]: https://adamwathan.me/refactoring-to-collections +[1]: https://laravel.com/docs/collections +[2]: /talks/using-laravel-collections-outside-laravel +[3]: https://www.drupal.org/project/collection_class +[4]: https://tighten.co +[5]: https://packagist.org/packages/tightenco/collect +[6]: https://laracasts.com/series/how-do-i/episodes/18 diff --git a/source/_posts/using-pcss-extension-postcss-webpack-encore.md b/source/_posts/using-pcss-extension-postcss-webpack-encore.md new file mode 100644 index 00000000..9033e5dc --- /dev/null +++ b/source/_posts/using-pcss-extension-postcss-webpack-encore.md @@ -0,0 +1,94 @@ +--- +title: Using the pcss extension for PostCSS with Webpack Encore +excerpt: How to use the .pcss file extension for PostCSS files with Webpack Encore. +date: 2020-04-01 +tags: + - encore + - postcss + - symfony + - webpack +--- + +I’ve been watching Christopher Pitt ([assertchris][assertchris-twitter])’s [streams on Twitch][assertchris-twitch] over the last few months, in one of which he was doing some work with Tailwind CSS and using a `.pcss` file extension for his PostCSS files. + +I couldn’t remember seeing this extension before, but this made a lot of sense to me compared to the standard `.css` extension - both to make it clear that it’s a PostCSS file and features like nesting can be used, and also for better integration and highlighting with IDEs and text editors such as PhpStorm. + +It’s also shorter that the `.postcss` extension, and has been suggested by [@PostCSS on Twitter](https://twitter.com/PostCSS/status/661645290622083073) previously. + +Some of my projects use [Laravel Mix][] which support this extension by default, but some of them use Symfony’s [Webpack Encore][] which didn’t seem to, so I decided to look into it. (Note that both are agnostic and not coupled to their respective frameworks, so can be used with other projects too including Drupal and Sculpin). + +## Updating Webpack Encore’s configuration + +I was able to review the existing configuration and confirm this by using `console.log()` to output Encore’s generated webpack configuration - specifically the module rules. + +```js +console.log(Encore.getWebpackConfig().module.rules) +``` + +There I can see the the test for PostCSS supports the `.css` and `.postcss` file extensions, but not `.pcss`. + +``` +test: /\.(css|postcss)$/, +``` + +There is documentation on the Symfony website for [adding custom webpack loaders and plugins](https://symfony.com/doc/current/frontend/encore/custom-loaders-plugins.html) but this wasn’t quite what I needed, as I needed to edit the existing `css` loader rather than add a new one. + +The page that I needed was [Advanced Webpack Config](https://symfony.com/doc/current/frontend/encore/advanced-config.html#having-the-full-control-on-loaders-rules) - specifically the section on 'Having the full control on Loaders Rules'. + +This suggests using `.configureLoaderRule()` and using that to override `test` directly. + +It does though come with a warning: + +> This is a low-level method. All your modifications will be applied just before pushing the loaders rules to Webpack. It means that you can override the default configuration provided by Encore, which may break things. Be careful when using it. + +My first pass was to add the full `.pcss` extension, but as this is a regular expression, I did a second pass that adds an second capturing group that would cover both PostCSS extensions. + +``` +// First pass +loaderRule.test = /\.(css|pcss|postcss)$/ + +// Second pass +loaderRule.test = /\.(css|p(ost)?css)$/ +``` + +To see this running, go to . + +## The final configuration + +This is my full `webpack.config.js` file for this site, including the `.pcss` extension support: + +```js +Encore + .disableSingleRuntimeChunk() + .cleanupOutputBeforeBuild() + .setOutputPath('source/build/') + .setPublicPath('/build') + .addEntry('app', './assets/js/app.js') + .enablePostCssLoader() + .configureLoaderRule('css', loaderRule => { + loaderRule.test = /\.(css|p(ost)?css)$/ + }) + .enableSourceMaps(!Encore.isProduction()) + +if (Encore.isProduction()) { + Encore + .enableVersioning() + .addPlugin(new PurgecssPlugin(purgecssConfig)) +} else { + Encore.enableSourceMaps() +} + +module.exports = Encore.getWebpackConfig() +``` + +Alternatively, you can view it in the [codebase on GitHub](https://github.com/opdavies/oliverdavies.uk/blob/796578d7f0f3332724cb8335982c69b36bc11e53/webpack.config.js). + +## Contributing back to Encore + +I’ve also submitted a pull request to Encore to add support for the `.pcss` extension by default: . If accepted, then these changes in `webpack.config.js` would no longer be needed. + +[assertchris-twitch]: https://www.twitch.tv/assertchris "assertchris on Twitch" +[assertchris-twitter]: https://twitter.com/assertchris "assertchris on Twitter" +[gitstore]: https://gitstore.app +[laravel mix]: https://laravel-mix.com +[webpack encore]: https://github.com/symfony/webpack-encore diff --git a/source/_posts/using-remote-files-when-developing-locally-stage-file-proxy-module.md b/source/_posts/using-remote-files-when-developing-locally-stage-file-proxy-module.md new file mode 100644 index 00000000..084212cf --- /dev/null +++ b/source/_posts/using-remote-files-when-developing-locally-stage-file-proxy-module.md @@ -0,0 +1,37 @@ +--- +title: Using Remote Files when Developing Locally with Stage File Proxy Module +date: 2014-11-20 +excerpt: How to install and configure the Stage File Proxy module to serve remote images on your local Drupal site. +tags: + - drupal + - drupal-planet + - servers +--- + +How to install and configure the +[Stage File Proxy](https://www.drupal.org/project/stage_file_proxy) module to +serve remote images on your local Drupal site. + +As this module is only going to be needed on pre-production sites, it would be +better to configure this within your settings.php or settings.local.php file. We +do this using the `$conf` array which removes the need to configure the module +through the UI and store the values in the database. + +```php +// File proxy to the live site. +$conf['stage_file_proxy_origin'] = 'http://www.example.com'; + +// Don't copy the files, just link to them. +$conf['stage_file_proxy_hotlink'] = TRUE; + +// Image style images are the wrong size otherwise. +$conf['stage_file_proxy_use_imagecache_root'] = FALSE; +``` + +If the origin site is not publicly accessible yet, maybe it's a pre-live or +staging site, and protected with a basic access authentication, you can include +the username and password within the origin URL. + +```php +$conf['stage_file_proxy_origin'] = 'http://user:password@prelive.example.com'; +``` diff --git a/source/_posts/using-tailwind-css-your-drupal-theme.md b/source/_posts/using-tailwind-css-your-drupal-theme.md new file mode 100644 index 00000000..2a81d89c --- /dev/null +++ b/source/_posts/using-tailwind-css-your-drupal-theme.md @@ -0,0 +1,112 @@ +--- +title: Using Tailwind CSS in your Drupal Theme +date: 2018-02-05 +excerpt: What is Tailwind CSS, and how do I use it in Drupal theme? +tags: + - drupal + - drupal-planet + - drupal-theming + - tailwind-css +--- + +## What is Tailwind? + +> Tailwind is a utility-first CSS framework for rapidly building custom user +> interfaces. + +It generates a number of utility classes that you can add to your theme's markup +to apply different styling, as well as the ability to apply classes to other +markup and create components comprised of utility classes using a custom +`@apply` PostCSS directive. + +## Initial Configuration + +The installation and configuration steps are essentially the same as those +outlined within the [Tailwind documentation][1], and should be performed within +your custom theme's directory (e.g. `sites/all/themes/custom/mytheme` for Drupal +7 or `themes/custom/mytheme` for Drupal 8: + +1. Require PostCSS and Tailwind via `npm` or `yarn`. +1. Generate a configuration file using `./node_modules/.bin/tailwind init`. +1. Tweak the settings as needed. +1. Add a `postcss.config.js` file. +1. Configure your build tool (Gulp, Grunt, Webpack). +1. Generate the CSS. +1. Include a path to the generated CSS in your `MYTHEME.info`, + `MYTHEME.info.yml` or `MYTHEME.libraries.yml` file. + +## PostCSS Configuration + +Create a `postcss.config.js` file and add `tailwindcss` as a plugin, passing the +path to the config file: + +```js +module.exports = { + plugins: [ + require('tailwindcss')('./tailwind.js'), + ] +} +``` + +## Configuration for Drupal + +There are some configuration settings within `tailwind.js` that you’ll need to +change to make things work nicely with Drupal. These are within the `options` +section: + +```js +options: { + prefix: 'tw-', + important: true, + ... +} +``` + +### Prefix + +By adding a prefix like `tw-`, we can ensure that the Tailwind classes don’t +conflict with core HTML classes like `block`. We can also ensure that they won't +conflict with any other existing HTML or CSS. + +No prefix: + +![](/images/blog/using-tailwind-drupal/prefix-1.png){.with-border} + +With prefix: + +![](/images/blog/using-tailwind-drupal/prefix-2.png){.with-border} + +### Important + +We can also set the `!important` rule on all Tailwind’s generated classes. We +need to do this if we want to override core styles which have more specific +rules. + +For example: if I had this core markup then the left margin added by `tw-ml-4` +would be overridden by core’s `.item-list ul` styling. + +```html +
+
    + ... +
+
+``` + +![](/images/blog/using-tailwind-drupal/important-1.png){.with-border} + +With the `!important` rule enabled though, the Tailwind’s class takes precedence +and is applied. + +![](/images/blog/using-tailwind-drupal/important-2.png){.with-border} + +## Example + +For an example of Tailwind within a Drupal 8 theme, see the custom theme for the +[Drupal Bristol website][0] on GitHub. + +[0]: + https://github.com/drupalbristol/drupal-bristol-website/tree/master/web/themes/custom/drupalbristol +[1]: https://tailwindcss.com/docs/installation +[2]: https://www.npmjs.com/get-npm +[3]: https://yarnpkg.com/lang/en/docs/install diff --git a/source/_posts/using-traefik-local-proxy-sculpin.md b/source/_posts/using-traefik-local-proxy-sculpin.md new file mode 100644 index 00000000..0f663c72 --- /dev/null +++ b/source/_posts/using-traefik-local-proxy-sculpin.md @@ -0,0 +1,64 @@ +--- +title: Using Traefik as a local proxy with Sculpin +tags: + - docker + - sculpin +draft: true +date: ~ +--- + + + +## Before + +```yaml +services: + app: + build: + context: . + dockerfile: tools/docker/images/Dockerfile + target: app + volumes: + - assets:/app/source/build + - /app/output_dev + - .:/app + ports: + - 8000:8000 +``` + +## Adding the proxy service + +```yaml +services: + proxy: + image: traefik:v2.0-alpine + command: + - --api.insecure=true + - --providers.docker + volumes: + - /var/run/docker.sock:/var/run/docker.sock + ports: + - 80:80 + - 8080:8080 + labels: + - "traefik.enable=false" +``` + +## Updating the app service + +```yaml +app: + build: + context: . + dockerfile: tools/docker/images/Dockerfile + target: app + expose: + - 80 + command: [generate, --server, --watch, --port, '80', --url, http://oliverdavies.localhost] + volumes: + - assets:/app/source/build + - /app/output_dev + - .:/app + labels: + - "traefik.http.routers.oliverdavies.rule=Host(`oliverdavies.localhost`)" +``` diff --git a/source/_posts/using-transition-props-vuejs.md b/source/_posts/using-transition-props-vuejs.md new file mode 100644 index 00000000..5d6d8d4c --- /dev/null +++ b/source/_posts/using-transition-props-vuejs.md @@ -0,0 +1,13 @@ +--- +title: Using Transition Class Props in Vue.js +date: 2019-06-06 +type: tweet +excerpt: Adam Wathan shows a more Tailwind-esque approach to writing Vue.js transitions. +tags: + - vuejs +external_url: https://twitter.com/adamwathan/status/1118670393030537217 +--- + +{% include 'tweet' with { + content: '🔥 Using the transition class props instead of the `name` prop for @vuejs transitions makes it really easy to compose transitions on the fly using utility classes.

This is how I do all my transitions in Vue these days — fits a lot better with the @tailwindcss philosophy 👌🏻 pic.twitter.com/shQCxaFZ8A

— Adam Wathan (@adamwathan) April 18, 2019' +} %} diff --git a/source/_posts/weeknotes-2021-06-05.md b/source/_posts/weeknotes-2021-06-05.md new file mode 100644 index 00000000..b9719fae --- /dev/null +++ b/source/_posts/weeknotes-2021-06-05.md @@ -0,0 +1,26 @@ +--- +title: 'Weeknotes: June 5th' +excerpt: Starting at Transport for Wales. +date: ~ +tags: + - personal + - week-notes +--- + +After the Bank Holiday weekend, I started working this week as a Lead Developer at [Transport for Wales](https://trc.cymru). I really enjoyed working at Inviqa, but felt that moving again to an in-house team would offer some new types of challenges whilst also getting to lead and manage a team. + +It's been an interesting first week, and I've met a lot of new colleagues whilst also going through the regular TfW induction processes and getting to know the current team. + +
+
+ +
+
Image
+
A screenshot of the tweet where I announced my move to Transport for Wales + +
+
+ +
+ +I'm looking forward to helping build and lead the development team at TfW, and plan on publishing regular weeknotes on the work that we're doing at Transport for Wales and TfW Rail. diff --git a/source/_posts/weeknotes-2021-06-12.md b/source/_posts/weeknotes-2021-06-12.md new file mode 100644 index 00000000..2c68a4bb --- /dev/null +++ b/source/_posts/weeknotes-2021-06-12.md @@ -0,0 +1,36 @@ +--- +title: 'Weeknotes: June 12th' +excerpt: Developing on Windows, organising dotfiles, and helping organise DrupalCon. +date: 2021-06-12 +tags: + - personal + - week-notes +--- + +## Local development with Windows and WSL 2 + +As a long-time Linux and macOS user, the last couple of weeks have been my first experience of using the Windows operating system for some time. After some research, I've been using the WSL 2 (Windows Subsystem for Linux) functionality built into Windows 10, with Ubuntu 20.04 installed within it. The codebase that I'm currently working on is using Lando, and that seems to be running fine within this setup after following some [instructions on the Lando documentation](https://docs.lando.dev/guides/setup-lando-on-windows-with-wsl-2.html) and a [blog post by Cal Evans](https://blog.calevans.com/2020/06/18/making-lando-work-inside-wsl2). + +I spend most of the day working within the WSL 2 environment which is a lot more familiar for me for development, but also for more simple tasks like generating SSH keys and cloning and configuring [my dotfiles](https://github.com/opdavies/dotfiles). + +## Re-organised dotfiles + +It was easy to clone my Dotfiles repository into the WSL 2 container but they still required to be symlinked into the correct place for them to be used. I'd previously used [rcm](https://github.com/thoughtbot/rcm), a tool from Thoughtbot, to do this but I wanted to review other approaches. + +I decided to try an approach of [using a local bare Git repository](https://www.atlassian.com/git/tutorials/dotfiles) and using Git's worktree functionality to clone the files into my home directory. This means no more symlinks, and no additional tool to manage the files. The structure of my dotfiles repo is now a lot simpler, though I do miss the grouping of files by 'tag' so I might look to re-implement this somehow in the future. + +## DrupalCon Europe kick-off meeting + +This week was the kick-off meeting for the DrupalCon Program Track Chair team, which I'm a part of this year. + +I've been proud to speak at the last two DrupalCon Europe conferences (2019 in Amsterdam, and online in 2020) and this year I wanted to contribute in a different way. + +I'm part of the Open Web & Community track and I'm looking forward to reviewing all of the sessions and experiencing DrupalCon in a new way again this year. + +## Inviqa blog post published + +My final task before leaving Inviqa a few weeks ago was to upgrade the inviqa.com and inviqa.de sites, which I co-developed, to Drupal 9. + +I wrote an article for the Inviqa blog, [Drupal 9 upgrade from Drupal 8](https://inviqa.com/blog/drupal-9-upgrade-from-drupal-8), which was published this week. + +I wrote my own post, [Upgrading the Dransible project to Drupal 9](/blog/upgrading-dransible-project-drupal-9) last year where I reviewed the commands and steps that I ran to upgrade one of my personal projects, whereas this post covers more about the process that we took, and the differences between this upgrade and previous Drupal upgrades that I've done. diff --git a/source/_posts/weeknotes-2021-07-24.md b/source/_posts/weeknotes-2021-07-24.md new file mode 100644 index 00000000..de5dfd10 --- /dev/null +++ b/source/_posts/weeknotes-2021-07-24.md @@ -0,0 +1,44 @@ +--- +title: 'Weeknotes: July 24th' +excerpt: Windows utilities, continuous integration and delivery, and writing tests. +tags: + - personal + - week-notes +date: ~ +--- + +## Using PowerToys and FancyZones + +I've been missing some of the features from Pop!_OS whilst working on my Windows laptop, so this week, I've been experimenting with [Microsoft PowerToys](https://docs.microsoft.com/en-us/windows/powertoys) which adds additional utilities to Windows 10 - similar to Gnome Tweak Tools. + +The main features that I'm trying are [FancyZones](https://docs.microsoft.com/en-us/windows/powertoys/fancyzones), which is similar to Pop!_OS's tiling window manager, and [Keyboard Manager](https://docs.microsoft.com/en-us/windows/powertoys/keyboard-manager](https://docs.microsoft.com/en-us/windows/powertoys/keyboard-manager)) so that I can remap some keys to match my personal laptop. + +## Continuous integration vs. feature branching + +I've been researching more about the continuous integration, or trunk-based development, approach to version control. Dave Farley's blog and [Continuous Delivery YouTube channel](https://www.youtube.com/channel/UCCfqyGl3nq_V0bo64CjZh8g) have been a great resource for this. I've also purchased his and Jez Humble's "Continuous Delivery" book, and have moved it to the top of my "To read" list. + +My current team at Transport for Wales is following a CI workflow, and it's been interesting to see code being pushed more often and moving from local to staging compared to waiting for async code reviews, so I'm looking forward to learning more about this approach and how to integrate it more with pair programming and test-driven development. + +I gave my first conference talk at DrupalCamp London 2014 on [Git Flow](/talks/git-flow), so I've been using the feature branch workflow for some time. As always, I'm willing to try and evaluate new approaches with an open mind. + +## Growing an automated test suite + +I [posted a tweet yesterday](https://twitter.com/opdavies/status/1418500778428338177) with a screenshot of the output from running some of the tests that I've added to my current work codebase. These are Drupal-based PHPUnit tests and are a combination of browser/functional and unit tests. + +I'm very keen on adding tests where possible for new functionality or when fixing bugs, which will make it much easier and less risky to refactor that code and ensure that the same bugs aren't re-added again. + +## Git hooks + +I've been using Git hooks for a few months to run checks locally, such as code linting and static analysis prior to pushing to a CI pipeline, to shorten the feedback loop and more quickly fix any failures. + +I've added some initial pre-push hooks to the current work codebase, to run some non-intrusive tasks such as code linting, with a view to adding to it over time. + +Sebastian Feldmann gave a talk in May for PHP South Wales, which included Git hooks. [The video is available on YouTube](https://www.youtube.com/watch?v=b85MoYmwUYs). + +## Deploying (and reverting) with CI and feature toggles + +Continuing with the CI/CD topic, I pushed a new, incomplete feature to production for one of my freelance clients' projects alongside some other changes. + +It was hidden behind a feature flag and not enabled, but it was merged and pushed to production. + +We decided to remove that implementation and use a different approach, so the code and the feature flag were removed, but for a time, that code was on production. diff --git a/source/_posts/weeknotes-2021-08-06.md b/source/_posts/weeknotes-2021-08-06.md new file mode 100644 index 00000000..d08f0a77 --- /dev/null +++ b/source/_posts/weeknotes-2021-08-06.md @@ -0,0 +1,32 @@ +--- +title: 'Weeknotes: August 6th' +excerpt: TODO +tags: + - personal + - week-notes +draft: true +date: ~ +--- + +## Vim + +- https://gist.github.com/opdavies/f944261b54f70b43f2297cab6779cf59 +- surround.vim - https://github.com/tpope/vim-surround +- https://towardsdatascience.com/how-i-learned-to-enjoy-vim-e310e53e8d56 + +## Re-watching invoice.space streams + +https://www.youtube.com/playlist?list=PLasJXc7CbyYfsdXu6t0406-kGwDN8aUG9 + +## Trialing Conventional Commits + +https://nitayneeman.com/posts/understanding-semantic-commit-messages-using-git-and-angular + +https://www.conventionalcommits.org/en/v1.0.0-beta.2 + +https://github.com/angular/angular/blob/22b96b9/CONTRIBUTING.md#-commit-message-guidelines + +https://github.com/vuejs/vue/commits/dev +https://github.com/vuejs/vue-cli/commits/dev + +https://github.com/pestphp/pest-intellij/commits/main diff --git a/source/_posts/what-git-flow.md b/source/_posts/what-git-flow.md new file mode 100644 index 00000000..5be5cbf3 --- /dev/null +++ b/source/_posts/what-git-flow.md @@ -0,0 +1,59 @@ +--- +title: 'DrupalCamp London: What is Git Flow?' +date: 2014-03-03 +excerpt: Here are my slides from my "What is Git Flow?" session at DrupalCamp London. +tags: + - git + - git-flow + - drupalcamp-london + - talks +tweets: true +--- + +Here are my slides from my "What is Git Flow?" session at +[DrupalCamp London](http://2014.drupalcamplondon.co.uk). + +{% include 'talk/slides' with { speakerdeck: { + data_id: '201559e0f103013198dd5a5f6f23ab67' } +} only %} + +## Take aways + +The main take aways are: + +- Git Flow adds various commands into Git to enhance its native functionality, + which creates a branching model to separate your stable production code from + your unstable development code. +- Never commit directly to the master branch - this is for production code only! +- You can commit directly to the develop branch, but this should be done + sparingly. +- Use feature branches as much as possible - one per feature, user story or bug. +- Commit early and often, and push to a remote often to encourage collaboration + as well as to provide a backup of your code. +- You can use settings within services like GitHub and Bitbucket to only allow + certain users to push to the master and develop branches, and restrict other + Developers to only commit and push to feature branches. Changes can then be + committed and pushed, then reviewed as part of a peer code review, and merged + back into the develop branch. + +## Feedback + +If you've got any questions, please feel free to +tweet at me +or fill in the +session +evaluation form that you can complete on the DrupalCamp London website. + +I've had some great feedback via Twitter: + +{% include 'tweet' with { + content: '

@opdavies @DrupalCampLDN always had trouble with git. Your talk + Git flow has made it all very easy.

— James Tombs (@jtombs) March 2, 2014' +} %} + +{% include 'tweet' with { + content: '

Great presentation by @opdavies on git flow at #dclondon very well prepared and presented. pic.twitter.com/tDINp2Nsbn

— Greg Franklin (@gfranklin) March 2, 2014' +} %} + +{% include 'tweet' with { + content: '

Great talk on git flow @opdavies #dclondon

— Curve Agency (@CurveAgency) March 2, 2014' +} %} diff --git a/source/_posts/writing-article-linux-journal.md b/source/_posts/writing-article-linux-journal.md new file mode 100644 index 00000000..13b5dc7b --- /dev/null +++ b/source/_posts/writing-article-linux-journal.md @@ -0,0 +1,22 @@ +--- +title: Writing an Article for Linux Journal +date: 2012-07-27 +excerpt: I'm absolutely delighted to announce that I'm going to be writing an article for Linux Journal magazine's upcoming Drupal special. +tags: + - distributions + - drupal + - installation-profiles + - linux-journal + - writing +--- + +I'm absolutely delighted to announce that I'm going to be writing an article for +[Linux Journal](http://www.linuxjournal.com) magazine's upcoming Drupal special. + +The article is going to be entitled "Speeding Up Your Drupal Development Using +Installation Profiles and Distributions" and will be mentioning existing +distributions available on Drupal.org, but mainly focussing on the steps needed +to create your own custom distribution. Needless to say, I'm quite excited about +it! + +The article is expected to be published in October. diff --git a/source/_posts/writing-info-file-drupal-7-theme.md b/source/_posts/writing-info-file-drupal-7-theme.md new file mode 100644 index 00000000..e3d623c1 --- /dev/null +++ b/source/_posts/writing-info-file-drupal-7-theme.md @@ -0,0 +1,40 @@ +--- +title: Writing a .info file for a Drupal 7 theme +date: 2012-05-23 +excerpt: An example .info file for a Drupal 7 theme. +tags: + - code + - drupal + - drupal-theming + - theming +--- + +```ini +name = My Theme +description = A description of my theme +core = 7.x + +# Add a base theme, if you want to use one. +base = mybasetheme + +# Define regions, otherwise the default regions will be used. +regions[header] = Header +regions[navigation] = Navigation +regions[content] = Content +regions[sidebar] = Sidebar +regions[footer] = Footer + +# Define which features are available. If none are specified, all the default +# features will be available. +features[] = logo +features[] = name +features[] = favicon + +# Add stylesheets +stylesheets[all][] = css/reset.css +stylesheets[all][] = css/mytheme.css +stylesheets[print][] = css/print.css + +# Add javascript files +styles[] = js/mytheme.js +``` diff --git a/source/_posts/writing-new-drupal-8-module-using-test-driven-development-tdd.md b/source/_posts/writing-new-drupal-8-module-using-test-driven-development-tdd.md new file mode 100644 index 00000000..d3990975 --- /dev/null +++ b/source/_posts/writing-new-drupal-8-module-using-test-driven-development-tdd.md @@ -0,0 +1,661 @@ +--- +title: Writing a new Drupal 8 Module using Test-Driven Development (TDD) +date: 2017-11-07 +tags: + - drupal + - phpunit + - simpletest + - tdd + - testing +excerpt: How to write automated tests and follow test driven development for Drupal modules. +meta: + image: + url: /images/talks/test-driven-drupal-development.png + width: 2560 + height: 1440 + type: image/png +promoted: true +--- + +

![](/images/blog/drupalcamp-dublin.jpg)

+ +I recently gave a [talk on automated testing in Drupal][0] talk at [DrupalCamp +Dublin][1] and as a lunch and learn session for my colleagues at Microserve. As +part of the talk, I gave an example of how to build a Drupal 8 module using a +test driven approach. I’ve released the [module code on GitHub][2], and this +post outlines the steps of the process. + +## Prerequisites + +You have created a `core/phpunit.xml` file based on `core/phpunit.xml.dist`, and +populated it with your database credentials so that PHPUnit can bootstrap the +Drupal database as part of the tests. [Here is an example][5]. + +## Acceptance Criteria + +For the module, we are going to satisfy this example acceptance criteria: + +> As a site visitor,
I want to see all published pages at /pages
Ordered +> alphabetically by title + +## Initial Setup + +Let’s start by writing the minimal code needed in order for the new module to be +enabled. In Drupal 8, this is the `.info.yml` file. + +```yaml +# tdd_dublin.info.yml + +name: 'TDD Dublin' +excerpt: 'A demo module for DrupalCamp Dublin to show test driven module development.' +core: 8.x +type: module +``` + +We can also add the test file structure at this point too. We’ll call it +`PageTestTest.php` and put it within a `tests/src/Functional` directory. As this +is a functional test, it extends the `BrowserTestBase` class, and we need to +ensure that the tdd_dublin module is enabled by adding it to the `$modules` +array. + +```php +// tests/src/Functional/PageListTest.php + +namespace Drupal\Tests\tdd_dublin\Functional; + +use Drupal\Tests\BrowserTestBase\BrowserTestBase; + +class PageListTest extends BrowserTestBase { + + protected static $modules = ['tdd_dublin']; + +} +``` + +With this in place, we can now start adding test methods. + +## Ensure that the Listing page Exists + +### Writing the First Test + +Let’s start by testing that the listing page exists at /pages. We can do this by +loading the page and checking the status code. If the page exists, the code will +be 200, otherwise it will be 404. + +I usually like to write comments first within the test method, just to outline +the steps that I'm going to take and then replace it with code. + +```php +public function testListingPageExists() { + // Go to /pages and check that it is accessible by checking the status + // code. +} +``` + +We can use the `drupalGet()` method to browse to the required path, i.e. +`/pages`, and then write an assertion for the response code value. + +```php +public function testListingPageExists() { + $this->drupalGet('pages'); + + $this->assertSession()->statusCodeEquals(200); +} +``` + +### Running the Test + +In order to run the tests, you either need to include `-c core` or be inside the +`core` directory when running the command, to ensure that the test classes are +autoloaded so can be found, though the path to the `vendor` directory may be +different depending on your project structure. You can also specify a path +within which to run the tests - e.g. within the module’s `test` directory. + +``` +$ vendor/bin/phpunit -c core modules/custom/tdd_dublin/tests +``` + +
+Note: I’m using Docksal, and I’ve noticed that I need to run the tests from within the CLI container. You can do this by running the `fin bash` command. +
+ +``` +1) Drupal\Tests\tdd_dublin\Functional\PageListTest::testListingPageExists +Behat\Mink\Exception\ExpectationException: Current response status code is 404, but 200 expected. + +FAILURES! +Tests: 1, Assertions: 1, Errors: 1. +``` + +Because the route does not yet exist, the response code returned is 404, so the +test fails. + +Now we can make it pass by adding the page. For this, I will use the Views +module, though you could achieve the same result with a custom route and a +Controller. + +### Building the View + +To begin with, I will create a view showing all types of content with a default +sort order of newest first. We will use further tests to ensure that only the +correct content is returned and that it is ordered correctly. + +![](/images/blog/tdd-drupal-1.png) { .with-border } + +The only addition I will make to the view is to add a path at `pages`, as per +the acceptance criteria. + +![](/images/blog/tdd-drupal-2.png) { .with-border } + +### Exporting the View + +With the first version of the view built, it needs to be incldued within the +module so that it can be enabled when the test is run. To do this, we need to +export the configuration for the view, and place it within the module’s +`config/install` directory. This can be done using the `drush config-export` +command or from within the Drupal UI. In either case, the `uid` line at the top +of the file needs to be removed so the configuration can be installed. + +Here is the exported view configuration: + +```yaml +langcode: en +status: true +dependencies: + module: + - node + - user +id: pages +label: pages +module: views +excerpt: '' +tag: '' +base_table: node_field_data +base_field: nid +core: 8.x +display: + default: + display_plugin: default + id: default + display_title: Master + position: 0 + display_options: + access: + type: perm + options: + perm: 'access content' + cache: + type: tag + options: { } + query: + type: views_query + options: + disable_sql_rewrite: false + distinct: false + replica: false + query_comment: '' + query_tags: { } + exposed_form: + type: basic + options: + submit_button: Apply + reset_button: false + reset_button_label: Reset + exposed_sorts_label: 'Sort by' + expose_sort_order: true + sort_asc_label: Asc + sort_desc_label: Desc + pager: + type: mini + options: + items_per_page: 10 + offset: 0 + id: 0 + total_pages: null + expose: + items_per_page: false + items_per_page_label: 'Items per page' + items_per_page_options: '5, 10, 25, 50' + items_per_page_options_all: false + items_per_page_options_all_label: '- All -' + offset: false + offset_label: Offset + tags: + previous: ‹‹ + next: ›› + style: + type: default + options: + grouping: { } + row_class: '' + default_row_class: true + uses_fields: false + row: + type: fields + options: + inline: { } + separator: '' + hide_empty: false + default_field_elements: true + fields: + title: + id: title + table: node_field_data + field: title + entity_type: node + entity_field: title + label: '' + alter: + alter_text: false + make_link: false + absolute: false + trim: false + word_boundary: false + ellipsis: false + strip_tags: false + html: false + hide_empty: false + empty_zero: false + settings: + link_to_entity: true + plugin_id: field + relationship: none + group_type: group + admin_label: '' + exclude: false + element_type: '' + element_class: '' + element_label_type: '' + element_label_class: '' + element_label_colon: true + element_wrapper_type: '' + element_wrapper_class: '' + element_default_classes: true + empty: '' + hide_alter_empty: true + click_sort_column: value + type: string + group_column: value + group_columns: { } + group_rows: true + delta_limit: 0 + delta_offset: 0 + delta_reversed: false + delta_first_last: false + multi_type: separator + separator: ', ' + field_api_classes: false + filters: + status: + value: '1' + table: node_field_data + field: status + plugin_id: boolean + entity_type: node + entity_field: status + id: status + expose: + operator: '' + group: 1 + sorts: + created: + id: created + table: node_field_data + field: created + order: DESC + entity_type: node + entity_field: created + plugin_id: date + relationship: none + group_type: group + admin_label: '' + exposed: false + expose: + label: '' + granularity: second + header: { } + footer: { } + empty: { } + relationships: { } + arguments: { } + display_extenders: { } + cache_metadata: + max-age: -1 + contexts: + - 'languages:language_content' + - 'languages:language_interface' + - url.query_args + - 'user.node_grants:view' + - user.permissions + tags: { } + page_1: + display_plugin: page + id: page_1 + display_title: Page + position: 1 + display_options: + display_extenders: { } + path: pages + cache_metadata: + max-age: -1 + contexts: + - 'languages:language_content' + - 'languages:language_interface' + - url.query_args + - 'user.node_grants:view' + - user.permissions + tags: { } +``` + +When the test is run again, we see a different error that leads us to the next +step. + +``` +1) Drupal\Tests\tdd_dublin\Functional\PageListTest::testListingPageExists +Drupal\Core\Config\UnmetDependenciesException: Configuration objects provided by tdd_dublin have unmet dependencies: node.type.page (node), views.view.pages (node, views) + +FAILURES! +Tests: 1, Assertions: 0, Errors: 1. +``` + +This error is identifying unmet dependencies within the module’s configuration. +In this case, the view that we’ve added depends on the node and views modules, +but these aren’t enabled. To fix this, we can add the extra modules as +dependencies of tdd_dublin so they will be enabled too. + +```yaml +# tdd_dublin.info.yml + +dependencies: + - drupal:node + - drupal:views +``` + +``` +1) Drupal\Tests\tdd_dublin\Functional\PageListTest::testListingPageExists +Drupal\Core\Config\UnmetDependenciesException: Configuration objects provided by tdd_dublin have unmet dependencies: views.view.pages (node.type.page) + +FAILURES! +Tests: 1, Assertions: 0, Errors: 1. +``` + +With the modules enabled, we can see one more unmet dependency for +`node.type.page`. This means that we need a page content type to be able to +install the view. We can fix this in the same way as before, by exporting the +configuration and copying it into the `config/install` directory. + +With this in place, the test should now pass - and it does. + +``` +Time: 26.04 seconds, Memory: 6.00MB + +OK (1 test, 1 assertion) +``` + +We now have a test to ensure that the listing page exists. + +## Ensure that only Published Pages are Shown + +### Writing the Test + +Now that we have a working page, we can now move on to checking that the correct +content is returned. Again, I’ll start by writing comments and then translate +that into code. + +The objectives of this test are: + +- To ensure that only page nodes are returned. +- To ensure that only published nodes are returned. + +```php +public function testOnlyPublishedPagesAreShown() { + // Given that a have a mixture of published and unpublished pages, as well + // as other types of content. + + // When I view the page. + + // Then I should only see the published pages. +} +``` + +In order to test the different scenarios, I will create an additional "article" +content type, create a node of this type as well as one published and one +unpublished page. From this combination, I only expect one node to be visible. + +```php +public function testOnlyPublishedPagesAreShown() { + $this->drupalCreateContentType(['type' => 'article']); + + $this->drupalCreateNode(['type' => 'page', 'status' => TRUE]); + $this->drupalCreateNode(['type' => 'article']); + $this->drupalCreateNode(['type' => 'page', 'status' => FALSE]); + + // When I view the page. + + // Then I should only see the published pages. +} +``` + +We could use `drupalGet()` again to browse to the page and write assertions +based on the rendered HTML, though I’d rather do this against the data returned +from the view itself. This is so that the test isn’t too tightly coupled to the +presentation logic, and we won’t be in a situation where at a later date the +test fails because of changes made to how the data is displayed. + +Rather, I’m going to use `views_get_view_result()` to programmatically get the +result of the view. This returns an array of `Drupal\views\ResultRow` objects, +which contain the nodes. I can use `array_column` to extract the node IDs from +the view result into an array. + +```php +public function testOnlyPublishedPagesAreShown() { + $this->drupalCreateContentType(['type' => 'article']); + + $this->drupalCreateNode(['type' => 'page', 'status' => TRUE]); + $this->drupalCreateNode(['type' => 'article']); + $this->drupalCreateNode(['type' => 'page', 'status' => FALSE]); + + $result = views_get_view_result('pages'); + $nids = array_column($result, 'nid'); + + // Then I should only see the published pages. +} +``` + +From the generated nodes, I can use `assertEquals()` to compare the returned +node IDs from the view against an array of expected node IDs - in this case, I +expect only node 1 to be returned. + +```php +public function testOnlyPublishedPagesAreShown() { + $this->drupalCreateContentType(['type' => 'article']); + + $this->drupalCreateNode(['type' => 'page', 'status' => TRUE]); + $this->drupalCreateNode(['type' => 'article']); + $this->drupalCreateNode(['type' => 'page', 'status' => FALSE]); + + $result = views_get_view_result('pages'); + $nids = array_column($result, 'nid'); + + $this->assertEquals([1], $nids); +} +``` + +### Running the Test + +The test fails as no extra conditions have been added to the view, though the +default "Content: Published" filter is already excluding one of the page nodes. +We can see from the output from the test that node 1 (a page) and node 2 (the +article) are both being returned. + +``` +1) Drupal\Tests\tdd_dublin\Functional\PageListTest::testOnlyPublishedPagesAreShown +Failed asserting that two arrays are equal. +--- Expected ++++ Actual +@@ @@ + Array ( +- 0 => 1 ++ 0 => '2' ++ 1 => '1' + ) + +FAILURES! +Tests: 1, Assertions: 3, Failures: 1. +``` + +### Updating the Test + +We can fix this by adding another condition to the view, to only show content +based on the node type - i.e. only return page nodes. + +![](/images/blog/tdd-drupal-3.png) { .with-border } + +Once the view is updated and the configuration is updated within the module, the +test should then pass - and it does. + +``` +Time: 24.76 seconds, Memory: 6.00MB + +OK (1 test, 3 assertions) +``` + +## Ensure that the Pages are in the Correct Order + +### Writing the Test + +As we know that the correct content is being returned, we can now focus on +displaying it in the correct order. We’ll start again by adding a new test +method and filling out the comments. + +```php +public function testResultsAreOrderedAlphabetically() { + // Given I have multiple nodes with different titles. + + // When I view the pages list. + + // Then I should see pages in the correct order. +} +``` + +To begin with this time, I’ll create a number of different nodes and specify the +title for each. These are intentionally in the incorrect order alphabetically so +that we can see the test fail initially and then see it pass after making a +change so we know that the change worked. + +```php +public function testResultsAreOrderedAlphabetically() { + $this->drupalCreateNode(['title' => 'Page A']); + $this->drupalCreateNode(['title' => 'Page D']); + $this->drupalCreateNode(['title' => 'Page C']); + $this->drupalCreateNode(['title' => 'Page B']); + + // When I view the pages list. + + // Then I should see pages in the correct order. +} +``` + +We can use the same method as the previous test to get the returned IDs, using +`views_get_view_result()` and `array_column()`, and assert that the returned +node IDs match the expected node IDs in the specified order. Based on the +defined titles, the order should be 1, 4, 3, 2. + +```php +public function testResultsAreOrderedAlphabetically() { + $this->drupalCreateNode(['title' => 'Page A']); + $this->drupalCreateNode(['title' => 'Page D']); + $this->drupalCreateNode(['title' => 'Page C']); + $this->drupalCreateNode(['title' => 'Page B']); + + $nids = array_column(views_get_view_result('pages'), 'nid'); + + $this->assertEquals([1, 4, 3, 2], $nids); +} +``` + +### Running the Test + +As expected the test fails, as the default sort criteria in the view orders the +results by their created date. + +In the test output, we can see the returned results are in sequential order so +the results array does not match the expected one. + +This would be particularly more complicated to test if I was using `drupalGet()` +and having to parse the HTML, compared to getting the results as an array from +the view programmatically. + +``` +1) Drupal\Tests\tdd_dublin\Functional\PageListTest::testResultsAreOrderedAlphabetically +Failed asserting that two arrays are equal. +--- Expected ++++ Actual +@@ @@ + Array ( +- 0 => 1 +- 1 => 4 +- 2 => 3 +- 3 => 2 ++ 0 => '1' ++ 1 => '2' ++ 2 => '3' ++ 3 => '4' + ) + +FAILURES! +Tests: 1, Assertions: 2, Failures: 1. +``` + +### Updating the Test + +This can be fixed by removing the default sort criteria and adding a new one +based on "Content: Title". + +![](/images/blog/tdd-drupal-4.png) { .with-border } + +Again, once the view has been updated and exported, the test should pass - and +it does. + +``` +Time: 27.55 seconds, Memory: 6.00MB + +OK (1 test, 2 assertions) +``` + +## Ensure all Tests Still Pass + +Now we know that all the tests pass individually, all of the module tests should +now be run to ensure that they all still pass and that there have been no +regressions due to any of the changes. + +``` +docker@cli:/var/www$ vendor/bin/phpunit -c core modules/custom/tdd_dublin/tests + +Testing modules/custom/tdd_dublin/tests +... + +Time: 1.27 minutes, Memory: 6.00MB + +OK (3 tests, 6 assertions) +``` + +They all pass, so we be confident that the code works as expected, we can +continue to refactor if needed, and if any changes are made to this module at a +later date, we have the tests to ensure that any regressions are caught and +fixed before deployment. + +## Next Steps + +I’ve started looking into whether some of the tests can be rewritten as kernel +tests, which should result in quicker test execution. I will post any updated +code to the [GitHub repository][3], and will also do another blog post +highlighting the differences between functional and kernel tests and the steps +taken to do the conversion. + +[0]: {{site.url}}/talks/tdd-test-driven-drupal +[1]: http://2017.drupal.ie +[2]: https://github.com/opdavies/tdd_dublin +[3]: https://packagist.org/packages/tightenco/collect +[4]: http://php.net/manual/en/function.array-column.php +[5]: https://gist.github.com/opdavies/dc5f0cea46ccd349b34a9f3a463c14bb diff --git a/source/_posts/zenophile.md b/source/_posts/zenophile.md new file mode 100644 index 00000000..b18e3114 --- /dev/null +++ b/source/_posts/zenophile.md @@ -0,0 +1,24 @@ +--- +title: Quickly Create Zen Subthemes Using Zenophile +date: 2010-05-10 +excerpt: How to use the Zenophile module to create a Zen subtheme. +tags: + - drupal-planet + - drupal-6 + - drupal-modules + - drupal-theming + - zen + - zenophile +--- + +If you use the [Zen](http://drupal.org/project/zen) theme, then you should also +be using the [Zenophile](http://drupal.org/project/zenophile) module! + +The Zenophile module allows you to very quickly create Zen subthemes from within +your web browser, as well as editing options such as the site directory where it +should be placed, the layout type (fixed or fluid), page wrapper and sidebar +widths, and the placement of the sidebars. + +For more information about the Zenophile module, check out +[this video](http://blip.tv/file/2427703) by +[Elliott Rothman](http://elliottrothman.com).