Commit 22e21801 authored by Robert Kasza's avatar Robert Kasza Committed by Robert Kasza
Browse files

Issue #3214545 by guilhermevp, gquisini, lucassc, Willy Christian, sophiavs,...

Issue #3214545 by guilhermevp, gquisini, lucassc, Willy Christian, sophiavs, diegors, tmaiochi, kaszarobert, victoria-marina, lucasbaralm: \Drupal calls should be avoided in classes, use dependency injection instead
parent b00bca44
Loading
Loading
Loading
Loading
+103 −41
Changes for README.md: 103 added lines, 41 removed lines.
Original line number Diff line number Diff line
@@ -12,55 +12,86 @@ Table of Contents

### Introduction

The Google Analytics Counter module is a scalable, lightweight page view counter which stores data collected by Google Analytics Counter in Drupal.
The Google Analytics Counter module is a scalable, lightweight page view counter
which stores data collected by Google Analytics Counter in Drupal.

The module features
- A custom field which contains the count of page views from Google Analytics API.
- A customizable block which contains the count of page views from Google Analytics API.
- A text filter which makes a token available. The token contains the page views from Google Analytics API.
- A custom field which contains the count of page views from
  Google Analytics API.
- A customizable block which contains the count of page views from
  Google Analytics API.
- A text filter which makes a token available. The token contains the page views
  from Google Analytics API.
- The data saved in Drupal can also be used for other things, like search.
- This module is suitable for large and high-traffic sites.

### Installation

1. Copy/upload the Google Analytics Counter module to the modules directory of your Drupal installation.
1. Copy/upload the Google Analytics Counter module to the modules directory of
your Drupal installation.

2. Enable the 'Google Analytics Counter' module in 'Extend'. (/admin/modules)

3. Set up user permissions. (/admin/people/permissions#module-google_analytics_counter)

4. Go to the settings page (/admin/config/system/google-analytics-counter). Review default settings and adjust accordingly.
   - For instance, the "Minimum time to wait before fetching Google Analytics data (in minutes)" field can usually be set to 0 except on the largest systems.
   - This setting, which may be deprecated in the future, is a setting which throttles the queries to Google. Since Google's quotas continue to increase as time goes on, this setting may just get in your way as you work to get the settings right for your system.
   - Likewise, on larger systems, it is probably preferable to increase the "Queue Time (in seconds)" so that all the queue items are processed in a single cron run.
4. Go to the settings page (/admin/config/system/google-analytics-counter).
Review default settings and adjust accordingly.
   - For instance, the "Minimum time to wait before fetching Google Analytics
     data (in minutes)" field can usually be set to 0 except on the
     largest systems.
   - This setting, which may be deprecated in the future, is a setting which
     throttles the queries to Google. Since Google's quotas continue to increase
     as time goes on, this setting may just get in your way as you work to get
     the settings right for your system.
   - Likewise, on larger systems, it is probably preferable to increase the
     "Queue Time (in seconds)" so that all the queue items are processed in a
     single cron run.

5. Click Save configuration.

6. Create a project in Google Analytics. For more information, see instruction in the README.md included with the module or Create a Project in Google Analytics page in this documentation.
6. Create a project in Google Analytics. For more information, see instruction
in the README.md included with the module or Create a Project in
Google Analytics page in this documentation.

7. Once your project in Google Analytics is ready, and you have your Google Project Client ID, Client Secret, Authorized Redirect URI and, optionally, Google Project Name, go to the authentication page. (/admin/config/system/google-analytics-counter/authentication)
7. Once your project in Google Analytics is ready, and you have your Google
Project Client ID, Client Secret, Authorized Redirect URI and, optionally,
Google Project Name, go to the authentication page.
(/admin/config/system/google-analytics-counter/authentication)

8. Add your Google Project Client ID, Client Secret, Authorized Redirect URI and, optionally, your Google Project Name to their likewise named fields on the authentication page.
   - See Create a Project in Google Analytics page in this documentation for how to set up a Google Analytics project.
8. Add your Google Project Client ID, Client Secret, Authorized Redirect URI
and, optionally, your Google Project Name to their likewise named fields on the
authentication page.
   - See Create a Project in Google Analytics page in this documentation for how
     to set up a Google Analytics project.

9. Usually the 'Authorized Redirect URI' field will be the authentication page in Drupal.
9. Usually the 'Authorized Redirect URI' field will be the authentication page
in Drupal.

10. The optional Google Project name field helps to take you directly to your Analytics API page to view Google's quotas. The Google Project name field should use the machine name of your Google project, like my-project. [Todo: add validation]
10. The optional Google Project name field helps to take you directly to your
Analytics API page to view Google's quotas. The Google Project name field should
use the machine name of your Google project, like my-project.
[Todo: add validation]

11. Click Save configuration.

12. Click the large button at the top of the page labeled 'Authenticate'.

13. In the pop up that appears from Google, select the google account to which you would like to authenticate.
13. In the pop up that appears from Google, select the google account to which
you would like to authenticate.

14. Fill in credentials if requested by Google.

15. Click Allow.

16. If all goes well, you will be returned to the authentication page in Drupal because that is the page you added to the 'Authorized Redirect URI field when setting up configuration in both Drupal and Google Analytics.
16. If all goes well, you will be returned to the authentication page in Drupal
because that is the page you added to the 'Authorized Redirect URI field when
setting up configuration in both Drupal and Google Analytics.

17. Select a view from the select list under Google View.
    - A good way to tell that authentication with Google has succeeded is if you see your google analytics profiles listed in the Google View. If you did not successfully authenticate with Google the only option in Google View is 'Unauthenticated'.
    - A good way to tell that authentication with Google has succeeded is if
      you see your google analytics profiles listed in the Google View. If you
      did not successfully authenticate with Google the only option in
      Google View is 'Unauthenticated'.

18. Click Save configuration.

@@ -68,11 +99,15 @@ The module features

20. Note: most of the numbers on the dashboard are 0 until you run cron.

21. Run cron. Generally speaking, it is a good idea to run cron continuously with a scheduler like Jenkins or a crontab to keep pageviews data in Drupal up to date with Google.
21. Run cron. Generally speaking, it is a good idea to run cron continuously
with a scheduler like Jenkins or a crontab to keep pageviews data in Drupal up
to date with Google.

22. Add the custom Google Analytics Counter field to one or more content type. See The custom Google Analytics Counter field for more information.
22. Add the custom Google Analytics Counter field to one or more content type.
See The custom Google Analytics Counter field for more information.

23. Place a Google Analytics Counter block on your site. (/admin/structure/block)
23. Place a Google Analytics Counter block on
your site. (/admin/structure/block)

24. Enable the text filter (More to come).

@@ -85,14 +120,17 @@ The module features
   - Click Create. Wait several moments for your project to be created.

3. Go to https://console.developers.google.com/apis/dashboard
   - You will most likely be directed to your project, or select your project by selecting your project's name in the upper left corner of the browser next to where it says Google APIS.
   - You will most likely be directed to your project, or select your project
     by selecting your project's name in the upper left corner of the browser
     next to where it says Google APIS.

4. Click Enable APIS and services on the Google APIs dashboard.
   - Search for Analytics API.
   - Click Analytics API.
   - On the proceeding page, click Enable.

5. You will be sent back to the Google APIs page. Click Credentials in the left-hand column.
5. You will be sent back to the Google APIs page. Click Credentials in the
left-hand column.

6. Click Create credentials. Select OAUTH client ID.

@@ -108,24 +146,34 @@ The module features
10. Leave the Authorized JavaScript origins field blank.

11. Add a url to the Authorized redirect URIs.
   - One of the Authorized redirect URI is usually the authentication page in Drupal. (admin/config/system/google-analytics-counter/authentication)
   - This is so you are redirected back to that page after authenticating in Drupal.
   - One of the Authorized redirect URI is usually the authentication page in
     Drupal. (admin/config/system/google-analytics-counter/authentication)
   - This is so you are redirected back to that page after authenticating in
     Drupal.
   - Example: http://localhost/d8/admin/config/system/google-analytics-counter/authentication
   - Click Create.
   - Click Create again.

12. Note your Client ID and Client secret.
   - You can also get your Client ID and client secret by going to the credentials page of your project (ex.: https://console.developers.google.com/apis/credentials?project=YOUR-PROJECT) and clicking the pencil icon on the right side across from your project name.
   - You can also get your Client ID and client secret by going to the
     credentials page of your project
     (ex.: https://console.developers.google.com/apis/credentials?project=YOUR-PROJECT)
     and clicking the pencil icon on the right side across from your project
     name.

13. Copy your client ID client secret, and Authorized redirect URIs from Google and add them to analytics authentication form in the module. (/admin/config/system/google-analytics-counter/authentication).
13. Copy your client ID client secret, and Authorized redirect URIs from Google
and add them to analytics authentication form in the module.
(/admin/config/system/google-analytics-counter/authentication).

### The Google Analytics Counter field.

Once added to a system, the custom Google Analytics Counter field is the same as any other field on a node except the field's value is from Google Analytics.
Once added to a system, the custom Google Analytics Counter field is the same as
any other field on a node except the field's value is from Google Analytics.

To add the custom Google Analytics Counter field to one or more contents.

1. Go to the Custom field configuration page /admin/config/system/google-analytics-counter-configure-types.
1. Go to the Custom field configuration
page /admin/config/system/google-analytics-counter-configure-types.

2. Click the content types you would like to add the field to.

@@ -134,7 +182,8 @@ To add the custom Google Analytics Counter field to one or more contents.

#### If you wish to remove the custom field from your system.

1. Go to the Custom field configuration page /admin/config/system/google-analytics-counter-configure-types.
1. Go to the Custom field configuration
page /admin/config/system/google-analytics-counter-configure-types.

2. Click the Remove the custom field checkbox.

@@ -152,24 +201,28 @@ At any time, you can add the custom field back to one or more content type

#### To add the custom field to the content type's edit form

1. Go to the Manage form display tab of the content type (Ex.: /admin/structure/types/manage/CONTENT-TYPE/form-display).
1. Go to the Manage form display tab of the
content type (Ex.: /admin/structure/types/manage/CONTENT-TYPE/form-display).

2. Move the Google Analytics Counter field out of the Disabled area.

3. Go to a node of that content type.

4. The data will already have been stored during cron runs unless the field had been previously completely removed from the system.
4. The data will already have been stored during cron runs unless the field had
been previously completely removed from the system.

5. If a cron run is needed. Run cron.


To add the custom field to the content type's view

1. Go to the Manage display tab of the content type (Ex.: /admin/structure/types/manage/CONTENT-TYPE/display).
1. Go to the Manage display tab of the
content type (Ex.: /admin/structure/types/manage/CONTENT-TYPE/display).

2. Move the Google Analytics Counter field out of the Disabled area.

4. The data will already have been stored during cron runs unless the field had been previously completely removed from the system.
4. The data will already have been stored during cron runs unless the field had
been previously completely removed from the system.

5. If a cron run is needed. Run cron.

@@ -177,19 +230,28 @@ To add the custom field to the content type's view

#### The custom field can also be added using standard Drupal procedures.

The only caveat to using standard Drupal procedures is the machine name of the field must be field_google_analytics_counter.
The only caveat to using standard Drupal procedures is the machine name of the
field must be field_google_analytics_counter.

Also If you add the custom field with standard Drupal procedures, you'll have to add the field to every content type you would like to see the pageview total on.
Also If you add the custom field with standard Drupal procedures, you'll have to
add the field to every content type you would like to see the pageview total on.

1. Go to the custom field tab (/admin/config/system/google-analytics-counter-configure-types)
1. Go to the custom
field tab (/admin/config/system/google-analytics-counter-configure-types)

2. Go to the content type you'd like to add the custom field to (/admin/structure/types/manage/form/fields)
2. Go to the content type you'd like to add the
custom field to (/admin/structure/types/manage/form/fields)

3. Click +Add field

4. Under Add a new field, select Number (integer)

5. Under Label, name the field Google Analytics Counter, which by default adds the machine name for the field field_google_analytics_counter. The machine name of the field is the key to getting the code to work. Make sure your field's machine name is field_google_analytics_counter. If you've never edited a machine name of a field before, remember that you input google_analytics_counter. Drupal adds the field_.
5. Under Label, name the field Google Analytics Counter, which by default adds
the machine name for the field field_google_analytics_counter. The machine name
of the field is the key to getting the code to work. Make sure your field's
machine name is field_google_analytics_counter. If you've never edited a machine
name of a field before, remember that you input google_analytics_counter.
Drupal adds the field_.

6. Click Save and continue.

@@ -199,10 +261,10 @@ Also If you add the custom field with standard Drupal procedures, you'll have to

9. Run cron.

10. See the pageview total in the edit form, the view of the node, or in a view that you create.
10. See the pageview total in the edit form, the view of the node, or in a view
that you create.

### Project Status

- [Google Analytics Counter](https://www.drupal.org/project/google_analytics_counter)
Author: Eric Sod (esod).
+8 −1
Changes for google_analytics_counter.install: 8 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -287,7 +287,7 @@ function google_analytics_counter_update_8009() {
  // Finally, if the {gac_type_} was checked, create the field config,
  // and check {gac_type_} again.
  foreach ($content_types as $machine_name => $content_type) {
    foreach ($gac_types as $key => $gac_type) {
    foreach ($gac_types as $gac_type) {
      if ($gac_type == $content_type->id()) {

        /** @var \Drupal\google_analytics_counter\GoogleAnalyticsCounterCustomFieldGeneratorInterface $custom_field */
@@ -486,3 +486,10 @@ function google_analytics_counter_update_8012() {
function google_analytics_counter_update_8013() {
  \Drupal::state()->delete('google_analytics_counter.cron_next_execution');
}

/**
 * Issue #3214545: Fixing ArgumentCountError after constructor parameter change.
 */
function google_analytics_counter_update_8014() {
  // Empty update hook for clearing cache.
}
+3 −3
Changes for google_analytics_counter.services.yml: 3 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -4,15 +4,15 @@ services:

  google_analytics_counter.app_manager:
    class: \Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManager
    arguments: ['@config.factory', '@database', '@state', '@path_alias.manager', '@path.matcher', '@language_manager', '@logger.channel.google_analytics_counter', '@messenger', '@google_analytics_counter.auth_manager']
    arguments: ['@config.factory', '@database', '@state', '@path_alias.manager', '@path.matcher', '@language_manager', '@logger.channel.google_analytics_counter', '@messenger', '@google_analytics_counter.auth_manager', '@path.current', '@current_route_match']

  google_analytics_counter.auth_manager:
    class: \Drupal\google_analytics_counter\GoogleAnalyticsCounterAuthManager
    arguments: ['@config.factory', '@database', '@state', '@logger.channel.google_analytics_counter', '@messenger']
    arguments: ['@config.factory', '@database', '@state', '@logger.channel.google_analytics_counter', '@messenger', '@request_stack']

  google_analytics_counter.custom_field_generator:
    class: Drupal\google_analytics_counter\GoogleAnalyticsCounterCustomFieldGenerator
    arguments: ['@config.factory', '@database', '@logger.channel.google_analytics_counter', '@messenger']
    arguments: ['@config.factory', '@database', '@logger.channel.google_analytics_counter', '@messenger', '@entity_type.manager', '@entity_display.repository']

  google_analytics_counter.message_manager:
    class: Drupal\google_analytics_counter\GoogleAnalyticsCounterMessageManager
+30 −5
Changes for src/Controller/GoogleAnalyticsCounterController.php: 30 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -4,7 +4,9 @@ namespace Drupal\google_analytics_counter\Controller;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Datetime\DateFormatter;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Url;
use Drupal\google_analytics_counter\GoogleAnalyticsCounterHelper;
@@ -70,7 +72,14 @@ class GoogleAnalyticsCounterController extends ControllerBase {
  protected $messageManager;

  /**
   * Constructs a Dashboard object.
   * Provides a redirect destinations.
   *
   * @var \Drupal\Core\Routing\RedirectDestinationInterface
   */
  protected $destination;

  /**
   * Constructs a GoogleAnalyticsCounterController object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
@@ -78,21 +87,35 @@ class GoogleAnalyticsCounterController extends ControllerBase {
   *   The state keyvalue collection to use.
   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
   *   The date formatter service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The environment time.
   * @param \Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManagerInterface $app_manager
   *   Google Analytics Counter App Manager object.
   * @param \Drupal\google_analytics_counter\GoogleAnalyticsCounterAuthManagerInterface $auth_manager
   *   Google Analytics Counter Auth Manager object.
   * @param \Drupal\google_analytics_counter\GoogleAnalyticsCounterMessageManagerInterface $message_manager
   *   Google Analytics Counter Manager object.
   * @param \Drupal\Core\Routing\RedirectDestinationInterface $destination
   *   Provides a redirect destinations.
   */
  public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, DateFormatter $date_formatter, GoogleAnalyticsCounterAppManagerInterface $app_manager, GoogleAnalyticsCounterAuthManagerInterface $auth_manager, GoogleAnalyticsCounterMessageManagerInterface $message_manager) {
  public function __construct(
    ConfigFactoryInterface $config_factory,
    StateInterface $state,
    DateFormatter $date_formatter,
    TimeInterface $time,
    GoogleAnalyticsCounterAppManagerInterface $app_manager,
    GoogleAnalyticsCounterAuthManagerInterface $auth_manager,
    GoogleAnalyticsCounterMessageManagerInterface $message_manager,
    RedirectDestinationInterface $destination
    ) {
    $this->config = $config_factory->get('google_analytics_counter.settings');
    $this->state = $state;
    $this->dateFormatter = $date_formatter;
    $this->time = \Drupal::service('datetime.time');
    $this->time = $time;
    $this->appManager = $app_manager;
    $this->authManager = $auth_manager;
    $this->messageManager = $message_manager;
    $this->destination = $destination;
  }

  /**
@@ -103,9 +126,11 @@ class GoogleAnalyticsCounterController extends ControllerBase {
      $container->get('config.factory'),
      $container->get('state'),
      $container->get('date.formatter'),
      $container->get('datetime.time'),
      $container->get('google_analytics_counter.app_manager'),
      $container->get('google_analytics_counter.auth_manager'),
      $container->get('google_analytics_counter.message_manager')
      $container->get('google_analytics_counter.message_manager'),
      $container->get('redirect.destination'),
    );
  }

@@ -341,7 +366,7 @@ class GoogleAnalyticsCounterController extends ControllerBase {
    ];

    // Run cron immediately.
    $destination = \Drupal::destination()->getAsArray();
    $destination = $this->destination->getAsArray();
    $t_args = [
      ':href' => Url::fromRoute('system.run_cron', [], [
        'absolute' => TRUE,
+28 −4
Changes for src/Form/GoogleAnalyticsCounterAuthForm.php: 28 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -5,12 +5,14 @@ namespace Drupal\google_analytics_counter\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\Core\Url;
use Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManagerInterface;
use Drupal\google_analytics_counter\GoogleAnalyticsCounterAuthManagerInterface;
use Drupal\google_analytics_counter\GoogleAnalyticsCounterHelper;
use Drupal\google_analytics_counter\GoogleAnalyticsCounterMessageManagerInterface;
use Drupal\Core\State\StateInterface;
use Drupal\path_alias\AliasManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
@@ -55,6 +57,20 @@ class GoogleAnalyticsCounterAuthForm extends ConfigFormBase {
   */
  protected $messageManager;

  /**
   * The current path for the current request.
   *
   * @var \Drupal\Core\Path\CurrentPathStack
   */
  protected $currentPath;

  /**
   * Find an alias for a path and vice versa.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Constructs a new SiteMaintenanceModeForm.
   *
@@ -68,14 +84,20 @@ class GoogleAnalyticsCounterAuthForm extends ConfigFormBase {
   *   Google Analytics Counter Auth Manager object.
   * @param \Drupal\google_analytics_counter\GoogleAnalyticsCounterMessageManagerInterface $message_manager
   *   Google Analytics Counter Message Manager object.
   * @param \Drupal\Core\Path\CurrentPathStack $current_path_stack
   *   The current path for the current request.
   * @param \Drupal\path_alias\AliasManagerInterface $alias_manager
   *   Find an alias for a path and vice versa.
   */
  public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, GoogleAnalyticsCounterAppManagerInterface $app_manager, GoogleAnalyticsCounterAuthManagerInterface $auth_manager, GoogleAnalyticsCounterMessageManagerInterface $message_manager) {
  public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, GoogleAnalyticsCounterAppManagerInterface $app_manager, GoogleAnalyticsCounterAuthManagerInterface $auth_manager, GoogleAnalyticsCounterMessageManagerInterface $message_manager, CurrentPathStack $current_path_stack, AliasManagerInterface $alias_manager) {
    parent::__construct($config_factory);
    $this->config = $config_factory->get('google_analytics_counter.settings');
    $this->state = $state;
    $this->appManager = $app_manager;
    $this->authManager = $auth_manager;
    $this->messageManager = $message_manager;
    $this->currentPath = $current_path_stack;
    $this->aliasManager = $alias_manager;
  }

  /**
@@ -87,7 +109,9 @@ class GoogleAnalyticsCounterAuthForm extends ConfigFormBase {
      $container->get('state'),
      $container->get('google_analytics_counter.app_manager'),
      $container->get('google_analytics_counter.auth_manager'),
      $container->get('google_analytics_counter.message_manager')
      $container->get('google_analytics_counter.message_manager'),
      $container->get('path.current'),
      $container->get('path_alias.manager')
    );
  }

@@ -178,8 +202,8 @@ class GoogleAnalyticsCounterAuthForm extends ConfigFormBase {
      '#weight' => 12,
    ];

    $current_path = \Drupal::service('path.current')->getPath();
    $uri = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
    $current_path = $this->currentPath->getPath();
    $uri = $this->aliasManager->getAliasByPath($current_path);
    $description = $this->t('The path that users are redirected to after they have authenticated with Google.<br /> Default: <strong>@default_uri</strong>', ['@default_uri' => $base_url . $uri]);
    $form['redirect_uri'] = [
      '#type' => 'textfield',
Loading