From 45a931f379f09b986e6f3a72bf964cb1bc321ea5 Mon Sep 17 00:00:00 2001 From: Nikolay Lobachev Date: Wed, 23 Aug 2023 12:22:17 +0200 Subject: [PATCH] Fix phpcs issues, add view processors, clean cache, fix comments plugins for nodes. --- ...iews.view.entity_activity_tracker_list.yml | 234 +++++++++--------- drush.services.yml | 4 + entity_activity_tracker.info.yml | 1 - entity_activity_tracker.install | 2 +- entity_activity_tracker.module | 7 + .../entity_activity_tracker_group.info.yml | 1 - .../CreditGroupContentCommentedEntity.php | 7 +- .../CreditGroupMembershipCommentCreation.php | 1 + .../CreditGroupMembershipContentCreation.php | 1 + .../src/Plugin/CreditGroupBase.php | 42 +++- .../Kernel/CreditGroupCommentCreationTest.php | 14 +- .../CreditGroupContentCommentedEntityTest.php | 8 +- .../Kernel/CreditGroupContentCreationTest.php | 12 +- ...editGroupMembershipCommentCreationTest.php | 18 +- ...editGroupMembershipContentCreationTest.php | 16 +- .../tests/src/Kernel/CreditGroupTestBase.php | 14 +- .../entity_activity_tracker_node.info.yml | 1 - .../CreditCommentedEntity.php | 17 +- .../CreditNodeForCommentCreationTest.php | 18 +- .../entity_activity_tracker_user.info.yml | 1 - .../Kernel/CreditUserCommentCreationTest.php | 13 +- .../Kernel/CreditUserContentCreationTest.php | 16 +- src/ActivityRecordStorage.php | 42 ++-- src/ActivityRecordStorageInterface.php | 2 +- .../EntityActivityTrackerCommands.php | 59 ++++- .../ExportActivityRecordsController.php | 48 +++- src/Entity/EntityActivityTracker.php | 12 +- src/EntityActivityTrackerFormsOperations.php | 6 +- ...EntityActivityTrackerHtmlRouteProvider.php | 10 - src/EntityActivityTrackerListBuilder.php | 45 +++- src/EntityActivityTrackerViewsOperations.php | 1 - src/EventSubscriber/ActivitySubscriber.php | 53 ++-- src/Form/EntityActivityTrackerDeleteForm.php | 2 +- src/Form/EntityActivityTrackerForm.php | 58 +++-- src/Form/ImportActivityRecordsForm.php | 16 +- src/Plugin/ActivityProcessor/EntityCreate.php | 23 +- src/Plugin/ActivityProcessor/EntityDecay.php | 10 +- src/Plugin/ActivityProcessor/EntityEdit.php | 16 +- src/Plugin/ActivityProcessor/EntityView.php | 78 ++++++ src/Plugin/ActivityProcessorBase.php | 43 +++- src/Plugin/ActivityProcessorCollection.php | 4 +- .../ActivityProcessorCreditRelatedBase.php | 13 +- src/Plugin/ActivityProcessorInterface.php | 15 +- src/Plugin/ActivityProcessorManager.php | 2 +- .../QueueWorker/ActivityProcessorQueue.php | 6 +- .../QueueWorker/ActivityQueueWorkerBase.php | 2 +- .../QueueWorker/CreditItemProcessorQueue.php | 8 +- .../QueueWorker/TrackerProcessorQueue.php | 4 +- src/Plugin/views/field/TrackedEntity.php | 15 +- src/QueueActivityItem.php | 61 +++++ src/TrackerLoader.php | 7 +- .../EntityActivityTrackerBasicPluginsTest.php | 24 +- .../Kernel/EntityActivityTrackerTestBase.php | 14 +- 53 files changed, 735 insertions(+), 412 deletions(-) create mode 100644 src/Plugin/ActivityProcessor/EntityView.php create mode 100644 src/QueueActivityItem.php diff --git a/config/optional/views.view.entity_activity_tracker_list.yml b/config/optional/views.view.entity_activity_tracker_list.yml index b28a110..b0c47e0 100644 --- a/config/optional/views.view.entity_activity_tracker_list.yml +++ b/config/optional/views.view.entity_activity_tracker_list.yml @@ -10,110 +10,13 @@ description: '' tag: '' base_table: entity_activity_tracker base_field: activity_id -core: 8.x display: default: - display_plugin: default id: default display_title: Master + display_plugin: default position: 0 display_options: - access: - type: none - options: { } - cache: - type: none - 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: table - options: - grouping: { } - row_class: '' - default_row_class: true - override: true - sticky: false - caption: '' - summary: '' - description: '' - columns: - tracked_entity: tracked_entity - activity: activity - created: created - changed: changed - info: - tracked_entity: - sortable: false - default_sort_order: asc - align: '' - separator: '' - empty_column: false - responsive: '' - activity: - sortable: true - default_sort_order: desc - align: '' - separator: '' - empty_column: false - responsive: '' - created: - sortable: true - default_sort_order: desc - align: '' - separator: '' - empty_column: false - responsive: '' - changed: - sortable: true - default_sort_order: desc - align: '' - separator: '' - empty_column: false - responsive: '' - default: '-1' - empty_table: false - row: - type: fields - options: - inline: { } - separator: '' - hide_empty: false - default_field_elements: true fields: tracked_entity: id: tracked_entity @@ -122,6 +25,7 @@ display: relationship: none group_type: group admin_label: '' + plugin_id: tracked_entity label: 'Tracked entity' exclude: false alter: @@ -163,7 +67,6 @@ display: hide_empty: false empty_zero: false hide_alter_empty: false - plugin_id: tracked_entity activity: id: activity table: entity_activity_tracker @@ -171,6 +74,7 @@ display: relationship: none group_type: group admin_label: '' + plugin_id: numeric label: Activity exclude: false alter: @@ -220,7 +124,6 @@ display: format_plural_string: !!binary MQNAY291bnQ= prefix: '' suffix: '' - plugin_id: numeric created: id: created table: entity_activity_tracker @@ -228,6 +131,7 @@ display: relationship: none group_type: group admin_label: '' + plugin_id: date label: Created exclude: false alter: @@ -272,7 +176,6 @@ display: date_format: html_date custom_date_format: '' timezone: '' - plugin_id: date changed: id: changed table: entity_activity_tracker @@ -280,6 +183,7 @@ display: relationship: none group_type: group admin_label: '' + plugin_id: date label: 'last changed' exclude: false alter: @@ -324,13 +228,55 @@ display: date_format: 'time ago' custom_date_format: '' timezone: '' - plugin_id: date - filters: { } - sorts: { } - header: { } - footer: { } + pager: + type: mini + options: + offset: 0 + items_per_page: 10 + total_pages: null + id: 0 + tags: + next: ›› + previous: ‹‹ + 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 + 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 + access: + type: none + options: { } + cache: + type: none + options: { } empty: { } - relationships: { } + sorts: + changed: + id: changed + table: entity_activity_tracker + field: changed + relationship: none + group_type: group + admin_label: '' + plugin_id: standard + order: DESC + expose: + label: '' + field_identifier: '' + exposed: false arguments: entity_type: id: entity_type @@ -339,6 +285,7 @@ display: relationship: none group_type: group admin_label: '' + plugin_id: string default_action: 'not found' exception: value: all @@ -353,8 +300,8 @@ display: summary_options: base_path: '' count: true - items_per_page: 25 override: false + items_per_page: 25 summary: sort_order: asc number_of_records: 0 @@ -370,7 +317,6 @@ display: path_case: none transform_dash: false break_phrase: false - plugin_id: string bundle: id: bundle table: entity_activity_tracker @@ -378,6 +324,7 @@ display: relationship: none group_type: group admin_label: '' + plugin_id: string default_action: 'not found' exception: value: all @@ -392,8 +339,8 @@ display: summary_options: base_path: '' count: true - items_per_page: 25 override: false + items_per_page: 25 summary: sort_order: asc number_of_records: 0 @@ -409,7 +356,72 @@ display: path_case: none transform_dash: false break_phrase: false - plugin_id: string + filters: { } + style: + type: table + options: + grouping: { } + row_class: '' + default_row_class: true + columns: + tracked_entity: tracked_entity + activity: activity + created: created + changed: changed + default: '-1' + info: + tracked_entity: + sortable: false + default_sort_order: asc + align: '' + separator: '' + empty_column: false + responsive: '' + activity: + sortable: true + default_sort_order: desc + align: '' + separator: '' + empty_column: false + responsive: '' + created: + sortable: true + default_sort_order: desc + align: '' + separator: '' + empty_column: false + responsive: '' + changed: + sortable: true + default_sort_order: desc + align: '' + separator: '' + empty_column: false + responsive: '' + override: true + sticky: false + summary: '' + empty_table: false + caption: '' + description: '' + row: + type: fields + options: + default_field_elements: true + inline: { } + separator: '' + hide_empty: false + query: + type: views_query + options: + query_comment: '' + disable_sql_rewrite: false + distinct: false + replica: false + query_tags: { } + relationships: { } + header: { } + footer: { } display_extenders: { } cache_metadata: max-age: -1 diff --git a/drush.services.yml b/drush.services.yml index 226d11c..dec7c47 100644 --- a/drush.services.yml +++ b/drush.services.yml @@ -1,5 +1,9 @@ services: entity_activity_tracker.commands: class: \Drupal\entity_activity_tracker\Commands\EntityActivityTrackerCommands + arguments: + - '@config.factory' + - '@database' + - '@config.storage' tags: - { name: drush.command } diff --git a/entity_activity_tracker.info.yml b/entity_activity_tracker.info.yml index 4f802f5..7c77860 100644 --- a/entity_activity_tracker.info.yml +++ b/entity_activity_tracker.info.yml @@ -1,7 +1,6 @@ name: 'Entity Activity Tracker' type: module description: 'Provides a way to track entity activity/popularity' -core: 8.x core_version_requirement: ^8 || ^9 package: 'Entity Activity Tracker' dependencies: diff --git a/entity_activity_tracker.install b/entity_activity_tracker.install index a288a3f..64f8f52 100644 --- a/entity_activity_tracker.install +++ b/entity_activity_tracker.install @@ -5,8 +5,8 @@ * Entity Activity Tracker module install/schema/update hooks. */ -use Drupal\Core\Entity\EntityTypeInterface; use Drupal\Core\Config\Entity\ConfigEntityStorage; +use Drupal\Core\Entity\EntityTypeInterface; /** * Implements hook_schema(). diff --git a/entity_activity_tracker.module b/entity_activity_tracker.module index bdbb9a8..57598dd 100644 --- a/entity_activity_tracker.module +++ b/entity_activity_tracker.module @@ -21,3 +21,10 @@ function entity_activity_tracker_help($route_name, RouteMatchInterface $route_ma default: } } + +/** + * Implements hook_preprocess_block(). + */ +function entity_activity_tracker_preprocess_block(&$variables) { + $test = $variables; +} diff --git a/modules/entity_activity_tracker_group/entity_activity_tracker_group.info.yml b/modules/entity_activity_tracker_group/entity_activity_tracker_group.info.yml index 8e3a83e..060cb21 100644 --- a/modules/entity_activity_tracker_group/entity_activity_tracker_group.info.yml +++ b/modules/entity_activity_tracker_group/entity_activity_tracker_group.info.yml @@ -1,7 +1,6 @@ name: 'Entity Activity Tracker - Group plugins' type: module description: 'Provides ActivityProcessor plugins specific to group entity type' -core: 8.x core_version_requirement: ^8 || ^9 package: 'Entity Activity Tracker' dependencies: diff --git a/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupContentCommentedEntity.php b/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupContentCommentedEntity.php index 11f265d..c73494b 100644 --- a/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupContentCommentedEntity.php +++ b/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupContentCommentedEntity.php @@ -164,8 +164,13 @@ public function isAccessible() { $content_plugin = $group_content_type->getContentPlugin(); $field_names = $this->commentManager->getFields($content_plugin->getEntityTypeId()); + foreach ($field_names as $field) { + if (!empty($field['bundles'][$content_plugin->getPluginDefinition()['entity_bundle']])) { + return TRUE; + } + } - return !empty($field_names['comment']['bundles'][$content_plugin->getEntityBundle()]); + return FALSE; } } diff --git a/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipCommentCreation.php b/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipCommentCreation.php index 7e17055..7c7dc86 100644 --- a/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipCommentCreation.php +++ b/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipCommentCreation.php @@ -153,4 +153,5 @@ public function isAccessible() { $group_content_type = $this->entityTypeManager->getStorage('group_content_type')->load($this->tracker->getTargetEntityBundle()); return $group_content_type->getContentPluginId() == 'group_membership'; } + } diff --git a/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipContentCreation.php b/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipContentCreation.php index 5136d92..2ed5d38 100644 --- a/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipContentCreation.php +++ b/modules/entity_activity_tracker_group/src/Plugin/ActivityProcessor/CreditGroupMembershipContentCreation.php @@ -152,4 +152,5 @@ public function isAccessible() { $group_content_type = $this->entityTypeManager->getStorage('group_content_type')->load($this->tracker->getTargetEntityBundle()); return $group_content_type->getContentPluginId() == 'group_membership'; } + } diff --git a/modules/entity_activity_tracker_group/src/Plugin/CreditGroupBase.php b/modules/entity_activity_tracker_group/src/Plugin/CreditGroupBase.php index aa1caf5..34cfc33 100644 --- a/modules/entity_activity_tracker_group/src/Plugin/CreditGroupBase.php +++ b/modules/entity_activity_tracker_group/src/Plugin/CreditGroupBase.php @@ -2,7 +2,6 @@ namespace Drupal\entity_activity_tracker_group\Plugin; -use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\entity_activity_tracker\Plugin\ActivityProcessorCreditRelatedBase; @@ -26,7 +25,6 @@ public function defaultConfiguration() { * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { - $form['credit_group'] = [ '#type' => 'number', '#title' => $this->t('Credit activity'), @@ -65,7 +63,7 @@ protected function getGroupContent(EntityInterface $entity) { if (empty($entity)) { return FALSE; } - $group_contents = $this->entityTypeManager->getStorage('group_content')->loadByEntity($entity); + $group_contents = $this->getGroupContentItemsByEntity($entity); if ($group_content = reset($group_contents)) { return $group_content; } @@ -85,8 +83,6 @@ protected function getGroup(GroupContentInterface $group_content) { // Prevent further execution if no group was found. if (empty($group)) { - // TODO: Use DI. - \Drupal::logger('entity_activity_tracker')->error($this->t("Couldn't find Group!")); return FALSE; } @@ -94,8 +90,6 @@ protected function getGroup(GroupContentInterface $group_content) { // Do something if there is a Tracker for group where content was created. if ($group_tracker) { - // I NEED TO THINK HOW TO HANDLE MULTIPLE. - // SINCE WE DON'T ALLOW A NODE BE PART OF 2 DIFFERENT GROUPS IT'S OK FOR NOW. return $group; } @@ -103,9 +97,13 @@ protected function getGroup(GroupContentInterface $group_content) { } /** + * Get groups by entity. + * * @param \Drupal\Core\Entity\EntityInterface $entity + * Entity. * * @return array + * Get groups by entity. */ protected function getGroupsByEntity(EntityInterface $entity) { $entities = []; @@ -116,8 +114,16 @@ protected function getGroupsByEntity(EntityInterface $entity) { return $entities; } + /** + * Get group content items by entity and bundle. + * + * @param \Drupal\Core\Entity\EntityInterface $entity + * Entity. + * + * @return \Drupal\Core\Entity\EntityInterface[] + * Group content items. + */ protected function getGroupContentItemsByEntityAndBundle(EntityInterface $entity) { - // TODO: Reorganize code to base classes. return $this->entityTypeManager->getStorage('group_content') ->loadByProperties([ 'entity_id' => $entity->id(), @@ -125,13 +131,29 @@ protected function getGroupContentItemsByEntityAndBundle(EntityInterface $entity ]); } + /** + * Get group content items by entity. + * + * @param \Drupal\Core\Entity\EntityInterface $entity + * Entity. + * + * @return mixed + * Group content items. + */ protected function getGroupContentItemsByEntity(EntityInterface $entity) { - // TODO: Reorganize code to base classes return $this->entityTypeManager->getStorage('group_content')->loadByEntity($entity); } + /** + * Get group content types for nodes. + * + * @param string $group_type_id + * Group type id. + * + * @return array + * Group content types for nodes + */ protected function getGroupContentTypesForNodes($group_type_id) { - // TODO: Reorganize code to base classes $group_type = $this->entityTypeManager->getStorage('group_type')->load($group_type_id); $group_content_plugins = []; diff --git a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupCommentCreationTest.php b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupCommentCreationTest.php index 38e192f..fa680d0 100755 --- a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupCommentCreationTest.php +++ b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupCommentCreationTest.php @@ -11,7 +11,7 @@ class CreditGroupCommentCreationTest extends CreditGroupTestBase { /** - * Test assignment of activity point when a comment for node inside of a group. + * Test assignment of activity point when a comment for node inside of group. */ public function testEntityCommenting() { $group = $this->createGroup(); @@ -28,7 +28,9 @@ public function testEntityCommenting() { } /** - * Test assignment of activity point when a new tracker is created and we want to assign points for existing comments in a group. + * Test assignment of activity point when a new tracker is created. + * + * And we want to assign points for existing comments in a group. */ public function testTrackerCreationExistingEntity() { $group = $this->createGroup(); @@ -44,12 +46,14 @@ public function testTrackerCreationExistingEntity() { $credit_group_comment_creation_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_group_comment_creation'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($group); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($credit_group_comment_creation_plugin_activity_point * $count, $activity_record->getActivityValue()); } /** - * Test assignment of activity point, when we create a tracker, but we don't have any comments in a group. + * Test assignment of activity point, when we create a tracker. + * + * But we don't have any comments in a group. */ public function testTrackerCreationWithNoEntities() { $tracker = $this->createTrackerForGroup(TRUE); @@ -61,7 +65,7 @@ public function testTrackerCreationWithNoEntities() { /** * Create a tracker for a group. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface diff --git a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCommentedEntityTest.php b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCommentedEntityTest.php index 7421f1f..5a3a0c1 100755 --- a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCommentedEntityTest.php +++ b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCommentedEntityTest.php @@ -5,7 +5,7 @@ use Drupal\group\Entity\GroupContent; /** - * Tests assignment of activity points for group content when someone comments it. + * Tests assignment of activity points for group content when someone comments. * * @group entity_activity_tracker * @see \Drupal\entity_activity_tracker_user\Plugin\ActivityProcessor\CreditGroupContentCommentedEntity @@ -33,7 +33,9 @@ public function testEntityCreation() { } /** - * Test assignment of activity points for group content, when a new tracker is created. + * Test assignment of activity points for group content. + * + * When a new tracker is created. */ public function testTrackerCreationExistingEntity() { $group = $this->createGroup(); @@ -68,7 +70,7 @@ public function testTrackerCreationWithNoEntities() { /** * Create a tracker for a group. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface diff --git a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCreationTest.php b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCreationTest.php index 8108be6..edd18cd 100755 --- a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCreationTest.php +++ b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupContentCreationTest.php @@ -3,7 +3,7 @@ namespace Drupal\Tests\entity_activity_tracker_group\Kernel; /** - * Tests assignment of activity points, when content is created inside of a group. + * Tests assignment of activity points, when content is created inside of group. * * @group entity_activity_tracker * @see \Drupal\entity_activity_tracker_user\Plugin\ActivityProcessor\CreditGroupContentCreation @@ -11,7 +11,7 @@ class CreditGroupContentCreationTest extends CreditGroupTestBase { /** - * Test assignment of activity points, when a new content is created in a group. + * Test assignment of activity points, when a new content is created in group. */ public function testEntityCommenting() { $group = $this->createGroup(); @@ -28,7 +28,9 @@ public function testEntityCommenting() { } /** - * Test assignment of activity points for existing nodes inside of a group, when a new tracker is created. + * Test assignment of activity points for existing nodes. + * + * Inside of a group, when a new tracker is created. */ public function testTrackerCreationExistingEntity() { $group = $this->createGroup(); @@ -42,7 +44,7 @@ public function testTrackerCreationExistingEntity() { $credit_group_comment_creation_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_group_content_creation'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($group); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($credit_group_comment_creation_plugin_activity_point * $count, $activity_record->getActivityValue()); } @@ -59,7 +61,7 @@ public function testTrackerCreationWithNoEntities() { /** * Create a tracker for a group. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface diff --git a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipCommentCreationTest.php b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipCommentCreationTest.php index c1d06e2..0c23046 100755 --- a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipCommentCreationTest.php +++ b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipCommentCreationTest.php @@ -3,7 +3,9 @@ namespace Drupal\Tests\entity_activity_tracker_group\Kernel; /** - * Test assignment of activity points to group membership when user posts comments. + * Test assignment of activity points to group membership. + * + * When user posts comments. * * @group entity_activity_tracker * @see \Drupal\entity_activity_tracker_user\Plugin\ActivityProcessor\CreditGroupMembershipCommentCreation @@ -11,10 +13,12 @@ class CreditGroupMembershipCommentCreationTest extends CreditGroupTestBase { /** - * Test assignment of activity points to group membership, when a new comment is posted. + * Test assignment of activity points to group membership. + * + * When a new comment is posted. */ public function testEntityCommenting() { - $group = $this->createGroup(); + $group = $this->createGroup();\ $group->addMember($this->adminUser); $tracker = $this->createTrackerForGroup(TRUE); $article = $this->createNode('article', FALSE); @@ -30,7 +34,9 @@ public function testEntityCommenting() { } /** - * Test assignment of activity points to group membership for existing comments, when a new tracker is created. + * Test assignment of activity points to group membership for. + * + * Existing comments, when a new tracker is created. */ public function testTrackerCreationExistingEntity() { $group = $this->createGroup(); @@ -46,7 +52,7 @@ public function testTrackerCreationExistingEntity() { $credit_group_membership_comment_creation_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_group_membership_comment_creation'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($membership->getGroupContent()); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($credit_group_membership_comment_creation_plugin_activity_point * $count, $activity_record->getActivityValue()); } @@ -63,7 +69,7 @@ public function testTrackerCreationWithNoEntities() { /** * Create a tracker for a group. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface diff --git a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipContentCreationTest.php b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipContentCreationTest.php index 16cb98d..91224c0 100755 --- a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipContentCreationTest.php +++ b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupMembershipContentCreationTest.php @@ -3,7 +3,9 @@ namespace Drupal\Tests\entity_activity_tracker_group\Kernel; /** - * Test assignment of activity points to group membership when user posts comments. + * Test assignment of activity points to group membership. + * + * When user posts comments. * * @group entity_activity_tracker * @see \Drupal\entity_activity_tracker_user\Plugin\ActivityProcessor\CreditGroupMembershipContentCreation @@ -11,7 +13,9 @@ class CreditGroupMembershipContentCreationTest extends CreditGroupTestBase { /** - * Test assignment of activity points to group membership, when a new node is posted. + * Test assignment of activity points to group membership. + * + * When a new node is posted. */ public function testEntityCommenting() { $group = $this->createGroup(); @@ -30,7 +34,9 @@ public function testEntityCommenting() { } /** - * Test assignment of activity points to group membership for existing nodes, when a new tracker is created. + * Test assignment of activity points to group membership for existing nodes. + * + * When a new tracker is created. */ public function testTrackerCreationExistingEntity() { $group = $this->createGroup(); @@ -45,7 +51,7 @@ public function testTrackerCreationExistingEntity() { $credit_group_membership_content_creation_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_group_membership_content_creation'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($membership->getGroupContent()); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($credit_group_membership_content_creation_plugin_activity_point * $count, $activity_record->getActivityValue()); } @@ -62,7 +68,7 @@ public function testTrackerCreationWithNoEntities() { /** * Create a tracker for a group. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface diff --git a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupTestBase.php b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupTestBase.php index 0408b1d..dfcd685 100755 --- a/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupTestBase.php +++ b/modules/entity_activity_tracker_group/tests/src/Kernel/CreditGroupTestBase.php @@ -70,20 +70,14 @@ protected function createGroup($run_cron = TRUE) { /** * Creates a group type. - * - * @param array $values - * (optional) The values used to create the entity. - * - * @return \Drupal\group\Entity\GroupType - * The created group type entity. */ protected function createGroupType() { $group_type_storage = $this->entityTypeManager->getStorage('group_type'); $this->groupType = $group_type_storage->create([ - 'id' => $this->randomMachineName(), - 'label' => $this->randomString(), - 'creator_membership' => FALSE, - ]); + 'id' => $this->randomMachineName(), + 'label' => $this->randomString(), + 'creator_membership' => FALSE, + ]); $group_type_storage->save($this->groupType); diff --git a/modules/entity_activity_tracker_node/entity_activity_tracker_node.info.yml b/modules/entity_activity_tracker_node/entity_activity_tracker_node.info.yml index 45b4e01..9e86d2d 100644 --- a/modules/entity_activity_tracker_node/entity_activity_tracker_node.info.yml +++ b/modules/entity_activity_tracker_node/entity_activity_tracker_node.info.yml @@ -1,7 +1,6 @@ name: 'Entity Activity Tracker - Node plugins' type: module description: 'Provides ActivityProcessor plugins specific to node entity type' -core: 8.x core_version_requirement: ^8 || ^9 package: 'Entity Activity Tracker' dependencies: diff --git a/modules/entity_activity_tracker_node/src/Plugin/ActivityProcessor/CreditCommentedEntity.php b/modules/entity_activity_tracker_node/src/Plugin/ActivityProcessor/CreditCommentedEntity.php index 4339a95..cfd3da3 100644 --- a/modules/entity_activity_tracker_node/src/Plugin/ActivityProcessor/CreditCommentedEntity.php +++ b/modules/entity_activity_tracker_node/src/Plugin/ActivityProcessor/CreditCommentedEntity.php @@ -2,7 +2,6 @@ namespace Drupal\entity_activity_tracker_node\Plugin\ActivityProcessor; -use Drupal\comment\CommentInterface; use Drupal\comment\CommentManagerInterface; use Drupal\Core\Database\Connection; use Drupal\Core\Entity\ContentEntityInterface; @@ -13,12 +12,12 @@ use Symfony\Component\DependencyInjection\ContainerInterface; /** - * Sets setting for nodes and preforms the activity process for nodes. + * Sets setting for nodes and performs the activity process for nodes. * * @ActivityProcessor ( * id = "credit_commented_entity", * event = "hook_event_dispatcher.entity.insert", - * label = @Translation("Credit Commented Entity"), + * label = @Translation("Credit commented node"), * entity_types = { * "node", * }, @@ -118,10 +117,10 @@ public function getConfigField() { /** * Get owner of the comment. * - * @param CommentInterface $comment + * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The comment attached to event. * - * @return ContentEntityInterface|null + * @return \Drupal\Core\Entity\ContentEntityInterface|null * Related entity or null. */ protected function getRelatedEntities(ContentEntityInterface $entity) { @@ -134,7 +133,13 @@ protected function getRelatedEntities(ContentEntityInterface $entity) { */ public function isAccessible() { $field_names = $this->commentManager->getFields('node'); - return !empty($field_names['comment']['bundles'][$this->tracker->getTargetEntityBundle()]); + foreach ($field_names as $field) { + if (!empty($field['bundles'][$this->tracker->getTargetEntityBundle()])) { + return TRUE; + } + } + + return FALSE; } /** diff --git a/modules/entity_activity_tracker_node/tests/src/Kernel/CreditNodeForCommentCreationTest.php b/modules/entity_activity_tracker_node/tests/src/Kernel/CreditNodeForCommentCreationTest.php index 4765f15..ed2f139 100755 --- a/modules/entity_activity_tracker_node/tests/src/Kernel/CreditNodeForCommentCreationTest.php +++ b/modules/entity_activity_tracker_node/tests/src/Kernel/CreditNodeForCommentCreationTest.php @@ -39,14 +39,14 @@ protected function setUp():void { /** * Create a tracker for node type article. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface * Tracker. */ protected function createTrackerForNodeArticle($run_cron) { - // @TODO: refactor hardcoded values. + // @todo refactor hardcoded values. return $this->createTracker('node', 'article', [ 'entity_create' => [ 'enabled' => 1, @@ -81,7 +81,9 @@ public function testEntityCommenting() { } /** - * Test assignment of activity points for existing nodes, when they have comments and we create a new tracker. + * Test assignment of activity points for existing nodes. + * + * When they have comments and we create a new tracker. */ public function testTrackerCreationExistingEntity() { $article = $this->createNode('article', TRUE); @@ -96,20 +98,20 @@ public function testTrackerCreationExistingEntity() { $credit_commented_entity_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_commented_entity'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($article); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($entity_create_plugin_activity_point + $credit_commented_entity_plugin_activity_point * $count, $activity_record->getActivityValue()); } /** - * Test that we don't assign any activity points when we create tracker and we don't have any existing entities. + * Test that we don't assign any activity points. + * + * When we create tracker and we don't have any existing entities. */ public function testTrackerCreationWithNoEntities() { $tracker = $this->createTrackerForNodeArticle(TRUE); $activity_records = $this->activityRecordStorage->getActivityRecordByBundle($tracker->getTargetEntityType(), $tracker->getTargetEntityBundle()); - $this->assertTrue( empty($activity_records)); + $this->assertTrue(empty($activity_records)); } - - } diff --git a/modules/entity_activity_tracker_user/entity_activity_tracker_user.info.yml b/modules/entity_activity_tracker_user/entity_activity_tracker_user.info.yml index 24d5812..ace89cc 100644 --- a/modules/entity_activity_tracker_user/entity_activity_tracker_user.info.yml +++ b/modules/entity_activity_tracker_user/entity_activity_tracker_user.info.yml @@ -1,7 +1,6 @@ name: 'Entity Activity Tracker - User plugins' type: module description: 'Provides ActivityProcessor plugins specific to user entity type' -core: 8.x core_version_requirement: ^8 || ^9 package: 'Entity Activity Tracker' dependencies: diff --git a/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserCommentCreationTest.php b/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserCommentCreationTest.php index a61433c..2b9f0aa 100755 --- a/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserCommentCreationTest.php +++ b/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserCommentCreationTest.php @@ -39,14 +39,13 @@ protected function setUp():void { /** * Create a tracker for a user. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface * Tracker. */ protected function createTrackerForUser($run_cron) { - // @TODO: refactor hardcoded values. return $this->createTracker('user', 'user', [ 'credit_user_comment_creation' => [ 'enabled' => 1, @@ -71,7 +70,9 @@ public function testEntityCommenting() { } /** - * Test assignment of activity points, when we create a tracker and we assign points to authors of comments. + * Test assignment of activity points, when we create a tracker and. + * + * We assign points to authors of comments. */ public function testTrackerCreationExistingEntity() { $article = $this->createNode('article', TRUE); @@ -84,12 +85,14 @@ public function testTrackerCreationExistingEntity() { $credit_user_comment_creation_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_user_comment_creation'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($this->adminUser); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($credit_user_comment_creation_plugin_activity_point * $count, $activity_record->getActivityValue()); } /** - * Test assignment of activity points, when we create a tracker and we don't have any comments. + * Test assignment of activity points. + * + * When we create a tracker and we don't have any comments. */ public function testTrackerCreationWithNoEntities() { $tracker = $this->createTrackerForUser(TRUE); diff --git a/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserContentCreationTest.php b/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserContentCreationTest.php index 33c3768..705db30 100755 --- a/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserContentCreationTest.php +++ b/modules/entity_activity_tracker_user/tests/src/Kernel/CreditUserContentCreationTest.php @@ -25,24 +25,16 @@ class CreditUserContentCreationTest extends EntityActivityTrackerTestBase { 'entity_activity_tracker_user', ]; - /** - * {@inheritdoc} - */ - protected function setUp():void { - parent::setUp(); - } - /** * Create a tracker for a user. * - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface * Tracker. */ protected function createTrackerForUser($run_cron) { - // @TODO: refactor hardcoded values. return $this->createTracker('user', 'user', [ 'credit_user_content_creation' => [ 'enabled' => 1, @@ -66,7 +58,9 @@ public function testNodeCreation() { } /** - * Test assignment of activity points, when we create a tracker and we assign points to authors of nodes. + * Test assignment of activity points. + * + * When we create a tracker and we assign points to authors of nodes. */ public function testTrackerCreationExistingEntity() { $count = 3; @@ -79,7 +73,7 @@ public function testTrackerCreationExistingEntity() { $credit_user_content_creation_plugin_activity_point = $this->getPluginActivityPoints($tracker, 'credit_user_content_creation'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($this->adminUser); - $this->assertTrue( !empty($activity_record)); + $this->assertTrue(!empty($activity_record)); $this->assertEquals($credit_user_content_creation_plugin_activity_point * $count, $activity_record->getActivityValue()); } diff --git a/src/ActivityRecordStorage.php b/src/ActivityRecordStorage.php index 84521cc..2300e3f 100644 --- a/src/ActivityRecordStorage.php +++ b/src/ActivityRecordStorage.php @@ -2,14 +2,14 @@ namespace Drupal\entity_activity_tracker; -use Drupal\Core\Database\Connection; -use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Component\Datetime\TimeInterface; +use Drupal\Core\Database\Connection; use Drupal\Core\Database\Query\SelectInterface; +use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Core\Logger\LoggerChannelFactoryInterface; /** - * Class ActivityRecordStorage. + * Class Activity Record Storage. */ class ActivityRecordStorage implements ActivityRecordStorageInterface { @@ -169,26 +169,26 @@ public function updateActivityRecord(ActivityRecord $activity_record) { * {@inheritdoc} */ public function decayActivityRecord(ActivityRecord $activity_record) { - if (!$activity_record->isNew()) { - $fields = [ - 'activity' => $activity_record->getActivityValue(), - 'changed' => $this->dateTime->getRequestTime(), - 'last_decay' => $this->dateTime->getRequestTime(), - ]; - try { - $this->database->update('entity_activity_tracker') - ->fields($fields) - ->condition('activity_id', $activity_record->id()) - ->execute(); - } - catch (\Throwable $th) { - $this->logger->error($th->getMessage()); - return FALSE; - } - return TRUE; + if ($activity_record->isNew()) { + return FALSE; } - return FALSE; + $fields = [ + 'activity' => $activity_record->getActivityValue(), + 'changed' => $this->dateTime->getRequestTime(), + 'last_decay' => $this->dateTime->getRequestTime(), + ]; + try { + $this->database->update('entity_activity_tracker') + ->fields($fields) + ->condition('activity_id', $activity_record->id()) + ->execute(); + } + catch (\Throwable $th) { + $this->logger->error($th->getMessage()); + return FALSE; + } + return TRUE; } /** diff --git a/src/ActivityRecordStorageInterface.php b/src/ActivityRecordStorageInterface.php index 6458286..8f0ed58 100644 --- a/src/ActivityRecordStorageInterface.php +++ b/src/ActivityRecordStorageInterface.php @@ -5,7 +5,7 @@ use Drupal\Core\Entity\ContentEntityInterface; /** - * Interface ActivityRecordStorageInterface. + * Interface Activity Record Storage. */ interface ActivityRecordStorageInterface { diff --git a/src/Commands/EntityActivityTrackerCommands.php b/src/Commands/EntityActivityTrackerCommands.php index 3660209..cce21cd 100644 --- a/src/Commands/EntityActivityTrackerCommands.php +++ b/src/Commands/EntityActivityTrackerCommands.php @@ -2,6 +2,9 @@ namespace Drupal\entity_activity_tracker\Commands; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Config\StorageInterface; +use Drupal\Core\Database\Connection; use Drush\Commands\DrushCommands; /** @@ -17,6 +20,47 @@ */ class EntityActivityTrackerCommands extends DrushCommands { + /** + * The config factory. + * + * @var \Drupal\Core\Config\ConfigFactoryInterface + */ + protected $configFactory; + + /** + * Database. + * + * @var \Drupal\Core\Database\Connection + */ + protected $database; + + /** + * The active configuration storage. + * + * @var \Drupal\Core\Config\StorageInterface + */ + protected $configStorage; + + /** + * FutTranslationsDrushCommands constructor. + * + * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory + * The config factory. + * @param \Drupal\Core\Database\Connection $database + * Database. + * @param \Drupal\Core\Config\StorageInterface $config_storage + * The active configuration storage. + */ + public function __construct( + ConfigFactoryInterface $config_factory, + Connection $database, + StorageInterface $config_storage, + ) { + $this->configFactory = $config_factory; + $this->database = $database; + $this->configStorage = $config_storage; + } + /** * Reset Entity Activity Tracker. * @@ -28,16 +72,15 @@ class EntityActivityTrackerCommands extends DrushCommands { */ public function resetEntityActivityTracker() { // Delete all existing configs. - $config_names = \Drupal::service('config.storage')->listAll('entity_activity_tracker'); - $config_factory = \Drupal::configFactory(); + $config_names = $this->configStorage->listAll('entity_activity_tracker'); foreach ($config_names as $config) { - $config_factory->getEditable($config)->delete(); + $this->configFactory->getEditable($config)->delete(); } - + // Truncate entity_activity_tracker and clean up queue. - $database = \Drupal::database(); - $database->truncate('entity_activity_tracker')->execute(); - $database->delete('queue')->condition('name', 'activity_processor_queue')->execute(); - $database->delete('queue')->condition('name', 'tracker_processor_queue')->execute(); + $this->database->truncate('entity_activity_tracker')->execute(); + $this->database->delete('queue')->condition('name', 'activity_processor_queue')->execute(); + $this->database->delete('queue')->condition('name', 'tracker_processor_queue')->execute(); } + } diff --git a/src/Controller/ExportActivityRecordsController.php b/src/Controller/ExportActivityRecordsController.php index 8d899b5..07f0ebd 100644 --- a/src/Controller/ExportActivityRecordsController.php +++ b/src/Controller/ExportActivityRecordsController.php @@ -5,12 +5,14 @@ use Drupal\Core\Config\ImmutableConfig; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Database\Connection; -use Symfony\Component\HttpFoundation\Response; +use Drupal\Core\Datetime\DateFormatterInterface; +use Drupal\Core\File\FileSystemInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; /** - * Class ExportActivityRecordsController. + * Class Export Activity Records Controller. */ class ExportActivityRecordsController extends ControllerBase { @@ -28,6 +30,20 @@ class ExportActivityRecordsController extends ControllerBase { */ protected $filesystemSettings; + /** + * The date formatter service. + * + * @var \Drupal\Core\Datetime\DateFormatterInterface + */ + protected $dateFormatter; + + /** + * File system. + * + * @var \Drupal\Core\File\FileSystemInterface + */ + protected $fileSystem; + /** * Constructs a new GroupMembershipController. * @@ -35,10 +51,21 @@ class ExportActivityRecordsController extends ControllerBase { * The active database connection. * @param \Drupal\Core\Config\ImmutableConfig $filesystem_settings * The 'system.file' config. + * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter + * The date formatter service. + * @param \Drupal\Core\File\FileSystemInterface $file_system + * File system. */ - public function __construct(Connection $database, ImmutableConfig $filesystem_settings) { + public function __construct( + Connection $database, + ImmutableConfig $filesystem_settings, + DateFormatterInterface $date_formatter, + FileSystemInterface $file_system + ) { $this->database = $database; $this->filesystemSettings = $filesystem_settings; + $this->dateFormatter = $date_formatter; + $this->fileSystem = $file_system; } /** @@ -47,7 +74,9 @@ public function __construct(Connection $database, ImmutableConfig $filesystem_se public static function create(ContainerInterface $container) { return new static( $container->get('database'), - $container->get('config.factory')->get('system.file') + $container->get('config.factory')->get('system.file'), + $container->get('date.formatter'), + $container->get('file_system') ); } @@ -59,7 +88,7 @@ public static function create(ContainerInterface $container) { */ public function export() { - // @TODO: Move it to ActivityRecords storage. + // @todo Move it to ActivityRecords storage. // Get everything from activity table;. $query = $this->database->select('entity_activity_tracker', 'fa') ->fields('fa'); @@ -67,7 +96,7 @@ public function export() { if ($first_row = $query->execute()->fetchAssoc()) { $temp_dir = $this->filesystemSettings->get('path.temporary'); - $temp_file = tempnam($temp_dir, 'activity_csv_export_'); + $temp_file = $this->fileSystem->tempnam($temp_dir, 'activity_csv_export_'); // Export to .CSV. $fp = fopen($temp_file, 'w'); @@ -78,15 +107,18 @@ public function export() { $rows = $query->execute()->fetchAllAssoc('activity_id', \PDO::FETCH_ASSOC); foreach ($rows as $row) { + $row['created'] = $this->dateFormatter->format($row['created'], 'd-m-Y H:i:s'); + $row['changed'] = $this->dateFormatter->format($row['changed'], 'd-m-Y H:i:s'); + $row['last_decay'] = $this->dateFormatter->format($row['last_decay'], 'd-m-Y H:i:s'); // Push the rest. fputcsv($fp, array_values((array) $row)); } fclose($fp); $file_content = file_get_contents($temp_file); - unlink($temp_file); + $this->fileSystem->unlink($temp_file); - $time = date('d_m_Y'); + $time = $this->dateFormatter->format(time(), 'd_m_Y'); $filename = "activity_export_{$time}.csv"; $response = new Response($file_content); diff --git a/src/Entity/EntityActivityTracker.php b/src/Entity/EntityActivityTracker.php index aaae32e..acc58b8 100644 --- a/src/Entity/EntityActivityTracker.php +++ b/src/Entity/EntityActivityTracker.php @@ -3,8 +3,8 @@ namespace Drupal\entity_activity_tracker\Entity; use Drupal\Core\Config\Entity\ConfigEntityBase; -use Drupal\entity_activity_tracker\Plugin\ActivityProcessorCollection; use Drupal\Core\Entity\EntityWithPluginCollectionInterface; +use Drupal\entity_activity_tracker\Plugin\ActivityProcessorCollection; /** * Defines the Entity activity tracker entity. @@ -129,16 +129,6 @@ public function getProcessorPlugin($instance_id) { return $this->getProcessorPlugins()->get($instance_id); } - public function getEnapledPluginById($instance_id) { - foreach ($this->getEnabledProcessorsPlugins() as $plguin) { - if ($plguin->getPluginId() == $instance_id) { - return $plguin; - } - } - - return NULL; - } - /** * {@inheritdoc} */ diff --git a/src/EntityActivityTrackerFormsOperations.php b/src/EntityActivityTrackerFormsOperations.php index 553c479..b5f4a8e 100644 --- a/src/EntityActivityTrackerFormsOperations.php +++ b/src/EntityActivityTrackerFormsOperations.php @@ -4,8 +4,8 @@ use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\DependencyInjection\DependencySerializationTrait; -use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Entity\ContentEntityInterface; +use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Messenger\MessengerInterface; use Drupal\Core\Session\AccountProxyInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; @@ -122,7 +122,7 @@ public function entityExtraFieldInfo() { public function formAlter(array &$form, FormStateInterface $form_state, $form_id) { if ($this->currentUser->hasPermission('access entity activity field') || $this->currentUser->hasPermission('administer activity trackers')) { - /** @var ContentEntityInterface $entity */ + /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ $entity = $form_state->getFormObject()->getEntity(); if ($entity instanceof ContentEntityInterface && !$entity->isNew() && $form_state->getFormObject()->getOperation() == 'edit' && $this->trackerLoader->hasTracker($entity) && $this->getActivityValue($entity)) { $form['activity'] = [ @@ -177,7 +177,7 @@ public function activitySubmit(array &$form, FormStateInterface $form_state) { /** * Get current activity value of given entity. * - * @param ContentEntityInterface $entity + * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The tracked entity. * * @return int diff --git a/src/EntityActivityTrackerHtmlRouteProvider.php b/src/EntityActivityTrackerHtmlRouteProvider.php index df7231e..0838d5b 100644 --- a/src/EntityActivityTrackerHtmlRouteProvider.php +++ b/src/EntityActivityTrackerHtmlRouteProvider.php @@ -2,7 +2,6 @@ namespace Drupal\entity_activity_tracker; -use Drupal\Core\Entity\EntityTypeInterface; use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider; /** @@ -13,14 +12,5 @@ */ class EntityActivityTrackerHtmlRouteProvider extends AdminHtmlRouteProvider { - /** - * {@inheritdoc} - */ - public function getRoutes(EntityTypeInterface $entity_type) { - $collection = parent::getRoutes($entity_type); - - // Provide your custom entity routes here. - return $collection; - } } diff --git a/src/EntityActivityTrackerListBuilder.php b/src/EntityActivityTrackerListBuilder.php index 28db4f7..2c8d9ad 100644 --- a/src/EntityActivityTrackerListBuilder.php +++ b/src/EntityActivityTrackerListBuilder.php @@ -4,12 +4,53 @@ use Drupal\Core\Config\Entity\ConfigEntityListBuilder; use Drupal\Core\Entity\EntityInterface; +use Drupal\Core\Entity\EntityStorageInterface; +use Drupal\Core\Entity\EntityTypeInterface; +use Drupal\Core\Render\RendererInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a listing of Entity activity tracker entities. */ class EntityActivityTrackerListBuilder extends ConfigEntityListBuilder { + /** + * The rendering service. + * + * @var \Drupal\Core\Render\RendererInterface + */ + protected $renderer; + + /** + * {@inheritdoc} + */ + public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) { + return new static( + $entity_type, + $container->get('entity_type.manager')->getStorage($entity_type->id()), + $container->get('renderer') + ); + } + + /** + * Constructs a new EntityListBuilder object. + * + * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type + * The entity type definition. + * @param \Drupal\Core\Entity\EntityStorageInterface $storage + * The entity storage class. + * @param \Drupal\Core\Render\RendererInterface $renderer + * The rendering service. + */ + public function __construct( + EntityTypeInterface $entity_type, + EntityStorageInterface $storage, + RendererInterface $renderer + ) { + parent::__construct($entity_type, $storage); + $this->renderer = $renderer; + } + /** * {@inheritdoc} */ @@ -34,8 +75,8 @@ public function buildRow(EntityInterface $entity) { '#markup' => $plugin->getSummary(), ]; } - // @TODO use DI. - $row['plugins'] = \Drupal::service('renderer')->render($summary_element); + + $row['plugins'] = $this->renderer->render($summary_element); return $row + parent::buildRow($entity); } diff --git a/src/EntityActivityTrackerViewsOperations.php b/src/EntityActivityTrackerViewsOperations.php index 35bfbab..4e16127 100644 --- a/src/EntityActivityTrackerViewsOperations.php +++ b/src/EntityActivityTrackerViewsOperations.php @@ -5,7 +5,6 @@ use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; -use Drupal\entity_activity_tracker\TrackerLoader; use Symfony\Component\DependencyInjection\ContainerInterface; /** diff --git a/src/EventSubscriber/ActivitySubscriber.php b/src/EventSubscriber/ActivitySubscriber.php index 91718c6..263ecc9 100644 --- a/src/EventSubscriber/ActivitySubscriber.php +++ b/src/EventSubscriber/ActivitySubscriber.php @@ -3,17 +3,16 @@ namespace Drupal\entity_activity_tracker\EventSubscriber; use Drupal\Core\Entity\ContentEntityInterface; -use Drupal\core_event_dispatcher\Event\Core\CronEvent; use Drupal\Core\Queue\QueueFactory; +use Drupal\core_event_dispatcher\EntityHookEvents; +use Drupal\core_event_dispatcher\Event\Core\CronEvent; use Drupal\core_event_dispatcher\Event\Entity\AbstractEntityEvent; -use Drupal\entity_activity_tracker\Event\TrackerCreateEvent; use Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface; -use Drupal\hook_event_dispatcher\Event\EventInterface; -use Drupal\hook_event_dispatcher\HookEventDispatcherInterface; +use Drupal\entity_activity_tracker\QueueActivityItem; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** - * Class ActivitySubscriber. + * Class Activity Subscriber. */ class ActivitySubscriber implements EventSubscriberInterface { @@ -54,6 +53,7 @@ public static function getSubscribedEvents() { // Replace with constants later. return [ 'hook_event_dispatcher.cron' => 'scheduleDecay', + 'hook_event_dispatcher.entity.view' => 'createActivityEvent', 'hook_event_dispatcher.entity.insert' => 'createActivityEvent', 'hook_event_dispatcher.entity.update' => 'createActivityEvent', 'hook_event_dispatcher.entity.delete' => 'deleteEntity', @@ -67,7 +67,8 @@ public static function getSubscribedEvents() { * The cron event. */ public function scheduleDecay(CronEvent $event) { - $this->queueEvent($event); + $queue_activity_item = new QueueActivityItem($event->getDispatcherType()); + $this->queueEvent($queue_activity_item); } /** @@ -77,68 +78,70 @@ public function scheduleDecay(CronEvent $event) { * The original event from which we dispatch activity event. */ public function createActivityEvent(AbstractEntityEvent $event) { - $entity = $event->getEntity(); + $queue_activity_item = new QueueActivityItem($event->getDispatcherType()); + $queue_activity_item->setEntity($entity); + $entity_type_id = $entity->getEntityTypeId(); // Add tracker handling to a queue. - if ($entity_type_id == 'entity_activity_tracker' && $event->getDispatcherType() == HookEventDispatcherInterface::ENTITY_INSERT) { - $this->queueTrackerEvent($event); + if ($entity_type_id == 'entity_activity_tracker' && $event->getDispatcherType() == EntityHookEvents::ENTITY_INSERT) { + $this->queueTrackerEvent($queue_activity_item); } // @todo IMPROVE THIS FIRST CONDITION!! // Syncing entities should not count. // @see: GroupContent::postSave() - // @todo: Move allowed entities to settings + // @todo Move allowed entities to settings if (!$entity->isSyncing() && in_array($entity_type_id, EntityActivityTrackerInterface::ALLOWED_ENTITY_TYPES)) { - $this->queueEvent($event); + $this->queueEvent($queue_activity_item); } } /** * Queue Activity events in ActivityProcessorQueue. * - * @param \Drupal\hook_event_dispatcher\Event\EventInterface $event - * Activity Event to queue. + * @param \Drupal\entity_activity_tracker\QueueActivityItem $queue_activity_item + * Queue activity item. */ - public function queueEvent($event) { - $this->createQueueEventItem($event, 'activity_processor_queue'); + public function queueEvent(QueueActivityItem $queue_activity_item) { + $this->createQueueEventItem($queue_activity_item, 'activity_processor_queue'); } /** * Queue tracker creation. * - * @param \Drupal\hook_event_dispatcher\Event\EventInterface $event - * Activity Event to queue. + * @param \Drupal\entity_activity_tracker\QueueActivityItem $queue_activity_item + * Queue activity item. */ - public function queueTrackerEvent(EventInterface $event) { - $this->createQueueEventItem($event, 'tracker_processor_queue'); + public function queueTrackerEvent(QueueActivityItem $queue_activity_item) { + $this->createQueueEventItem($queue_activity_item, 'tracker_processor_queue'); } /** * Create a queue event item. * - * @param \Drupal\hook_event_dispatcher\Event\EventInterface $event - * An event. + * @param \Drupal\entity_activity_tracker\QueueActivityItem $queue_activity_item + * Queue activity item. * @param string $queue_name * Queue name. */ - public function createQueueEventItem(EventInterface $event, $queue_name) { + public function createQueueEventItem(QueueActivityItem $queue_activity_item, $queue_name) { $processors_queue = $this->queue->get($queue_name); - $processors_queue->createItem($event); + $processors_queue->createItem($queue_activity_item); } /** * Delete entity event processing. * - * @param \Drupal\core_event_dispatcher\Event\Entity\AbstractEntityEvent $event + * @param \Drupal\core_event_dispatcher\Event\Entity\AbstractEntityEvent $original_event * The original event. */ public function deleteEntity(AbstractEntityEvent $original_event) { /** @var \Drupal\Core\Entity\EntityInterface|\Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface $entity */ $entity = $original_event->getEntity(); - // @TODO - Later we can move it in queue. + // @todo Later we can move it in queue. if ($entity->getEntityTypeId() == 'entity_activity_tracker') { // Clean all activity records for the tracker. $this->activityRecordStorage->deleteActivityRecorsdByBundle($entity->getTargetEntityType(), $entity->getTargetEntityBundle()); diff --git a/src/Form/EntityActivityTrackerDeleteForm.php b/src/Form/EntityActivityTrackerDeleteForm.php index 34d70cf..c0dda2a 100644 --- a/src/Form/EntityActivityTrackerDeleteForm.php +++ b/src/Form/EntityActivityTrackerDeleteForm.php @@ -5,8 +5,8 @@ use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Entity\EntityConfirmFormBase; use Drupal\Core\Form\FormStateInterface; -use Drupal\Core\Url; use Drupal\Core\Messenger\MessengerInterface; +use Drupal\Core\Url; use Symfony\Component\DependencyInjection\ContainerInterface; /** diff --git a/src/Form/EntityActivityTrackerForm.php b/src/Form/EntityActivityTrackerForm.php index 6bd5dc7..5f5767f 100644 --- a/src/Form/EntityActivityTrackerForm.php +++ b/src/Form/EntityActivityTrackerForm.php @@ -2,25 +2,24 @@ namespace Drupal\entity_activity_tracker\Form; -use Drupal\Core\Ajax\RemoveCommand; -use Drupal\Core\Entity\EntityForm; -use Drupal\Core\Form\FormStateInterface; -use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Component\Plugin\PluginManagerInterface; use Drupal\Core\Ajax\AjaxResponse; +use Drupal\Core\Ajax\RemoveCommand; use Drupal\Core\Ajax\ReplaceCommand; +use Drupal\Core\Cache\CacheBackendInterface; +use Drupal\Core\Entity\ContentEntityInterface; +use Drupal\Core\Entity\EntityForm; +use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Form\FormBuilderInterface; -use Drupal\entity_activity_tracker\Plugin\ActivityProcessorInterface; -use Drupal\entity_activity_tracker\TrackerLoader; -use Symfony\Component\DependencyInjection\ContainerInterface; +use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Form\SubformState; -use Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface; -use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Messenger\MessengerInterface; -use Drupal\Core\Cache\CacheBackendInterface; +use Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface; +use Drupal\entity_activity_tracker\TrackerLoader; +use Symfony\Component\DependencyInjection\ContainerInterface; /** - * Class EntityActivityTrackerForm. + * Class Entity Activity Tracker Form. */ class EntityActivityTrackerForm extends EntityForm { @@ -69,26 +68,26 @@ class EntityActivityTrackerForm extends EntityForm { /** * Entity type options. * - * @var array $entity_type_options + * @var array * List of entity types */ - protected $entity_type_options = []; + protected $entityTypeOptions = []; /** * Entity type bundles. * - * @var array $entity_type_bundles + * @var array * List of entity type bundles */ - protected $entity_type_bundles = []; + protected $entityTypeBundles = []; /** * Bundle options. * - * @var array $bundle_options + * @var array * List of bundle options */ - protected $bundle_options = []; + protected $bundleOptions = []; /** * {@inheritdoc} @@ -163,13 +162,13 @@ public function form(array $form, FormStateInterface $form_state) { '#disabled' => !$entity_activity_tracker->isNew(), ]; - if (empty($this->entity_type_options)) { + if (empty($this->entityTypeOptions)) { foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { if ($entity_type->entityClassImplements(ContentEntityInterface::class) && in_array($entity_type_id, EntityActivityTrackerInterface::ALLOWED_ENTITY_TYPES)) { - $this->entity_type_options[$entity_type_id] = $entity_type->get('label'); + $this->entityTypeOptions[$entity_type_id] = $entity_type->get('label'); // User don't have bundles. - $this->entity_type_bundles[$entity_type_id] = $entity_type->getBundleEntityType() ? $entity_type->getBundleEntityType() : $entity_type_id; + $this->entityTypeBundles[$entity_type_id] = $entity_type->getBundleEntityType() ? $entity_type->getBundleEntityType() : $entity_type_id; } } } @@ -179,7 +178,7 @@ public function form(array $form, FormStateInterface $form_state) { '#title' => $this->t('Entity Type'), '#description' => $this->t('Select entity type for this config.'), '#default_value' => $entity_activity_tracker->getTargetEntityType(), - '#options' => $this->entity_type_options, + '#options' => $this->entityTypeOptions, '#required' => TRUE, '#ajax' => [ 'callback' => [$this, 'updateBundlesElement'], @@ -202,7 +201,7 @@ public function form(array $form, FormStateInterface $form_state) { '#type' => 'select', '#title' => $this->t('Entity Bundle'), '#default_value' => $entity_activity_tracker->getTargetEntityBundle(), - '#options' => $this->getBundleOptions($this->entity_type_bundles[$entity_type]), + '#options' => $this->getBundleOptions($this->entityTypeBundles[$entity_type]), '#disabled' => !$entity_activity_tracker->isNew(), '#required' => TRUE, '#ajax' => [ @@ -228,14 +227,13 @@ public function form(array $form, FormStateInterface $form_state) { $processor_config = $entity_activity_tracker->get('activity_processors'); $target_entity_type = $entity_activity_tracker->getTargetEntityType(); - $target_bundle = $form_state->getValue('entity_bundle'); foreach ($this->manager->getDefinitions() as $plugin_id => $definition) { // Display plugins that are meant to track selected entity type. if (in_array($target_entity_type, $definition['entity_types'])) { - /** @var ActivityProcessorInterface $processor */ + /** @var \Drupal\entity_activity_tracker\Plugin\ActivityProcessorInterface $processor */ $processor = $entity_activity_tracker->getProcessorPlugin($plugin_id); - if (!$processor->isAccessible($target_bundle)) { + if (!$processor->isAccessible()) { continue; } // Check if processor is defined as required for entity type. @@ -405,22 +403,22 @@ public function updateProcessorsElement(array $form, FormStateInterface $form_st */ protected function getBundleOptions(string $entity_type_value) { - if (empty($this->bundle_options[$entity_type_value])) { - $this->bundle_options[$entity_type_value][''] = $this->t('- Select -'); + if (empty($this->bundleOptions[$entity_type_value])) { + $this->bundleOptions[$entity_type_value][''] = $this->t('- Select -'); if ($entity_type_value == 'user') { // User entities don't have bundle. - $this->bundle_options[$entity_type_value][$entity_type_value] = $this->t('User'); + $this->bundleOptions[$entity_type_value][$entity_type_value] = $this->t('User'); } else { $bundles = $this->entityTypeManager->getStorage($entity_type_value)->loadMultiple(); foreach ($bundles as $bundle_id => $bundle_type) { - $this->bundle_options[$entity_type_value][$bundle_id] = $bundle_type->get('name') ?? $bundle_id; + $this->bundleOptions[$entity_type_value][$bundle_id] = $bundle_type->get('name') ?? $bundle_id; } } } - return $this->bundle_options[$entity_type_value]; + return $this->bundleOptions[$entity_type_value]; } } diff --git a/src/Form/ImportActivityRecordsForm.php b/src/Form/ImportActivityRecordsForm.php index 8fef259..fcea7a2 100644 --- a/src/Form/ImportActivityRecordsForm.php +++ b/src/Form/ImportActivityRecordsForm.php @@ -7,8 +7,6 @@ use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\entity_activity_tracker\ActivityRecord; -use Drupal\entity_activity_tracker\ActivityRecordStorageInterface; -use Drupal\file\FileInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -85,7 +83,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $csv_file = $form_state->getValue('import_csv'); - /** @var FileInterface $file */ + /** @var \Drupal\file\FileInterface $file */ $file = $this->entityTypeManager->getStorage('file')->load($csv_file[0]); // TEST IF THIS CAN BE TEMPORARY. @@ -95,14 +93,20 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $operations = []; $data = $this->csvtoarray($file->getFileUri(), ','); foreach ($data as $row) { - $operations[] = ['\Drupal\entity_activity_tracker\Form\ImportActivityRecordsForm::addImportActivityRecord', [$row]]; + $operations[] = [ + '\Drupal\entity_activity_tracker\Form\ImportActivityRecordsForm::addImportActivityRecord', + [$row], + ]; } $batch = [ 'title' => $this->t('Importing Data...'), 'operations' => $operations, 'init_message' => $this->t('Import is starting.'), - 'finished' => ['\Drupal\entity_activity_tracker\Form\ImportActivityRecordsForm', 'addImportActivityRecordCallback'], + 'finished' => [ + '\Drupal\entity_activity_tracker\Form\ImportActivityRecordsForm', + 'addImportActivityRecordCallback', + ], ]; batch_set($batch); } @@ -156,7 +160,7 @@ public static function addImportActivityRecord(array $item, array &$context) { $bundle = $item['bundle']; $entity_id = $item['entity_id']; - /** @var ActivityRecordStorageInterface $activity_record_storage */ + /** @var \Drupal\entity_activity_tracker\ActivityRecordStorageInterface $activity_record_storage */ $activity_record_storage = \Drupal::service('entity_activity_tracker.activity_record_storage'); $item_storage = \Drupal::entityTypeManager()->getStorage($entity_type); $item_entity = $item_storage->load($entity_id); diff --git a/src/Plugin/ActivityProcessor/EntityCreate.php b/src/Plugin/ActivityProcessor/EntityCreate.php index eaacf9e..dfe6a82 100644 --- a/src/Plugin/ActivityProcessor/EntityCreate.php +++ b/src/Plugin/ActivityProcessor/EntityCreate.php @@ -2,8 +2,9 @@ namespace Drupal\entity_activity_tracker\Plugin\ActivityProcessor; -use Drupal\entity_activity_tracker\Plugin\ActivityProcessorBase; use Drupal\Core\Form\FormStateInterface; +use Drupal\entity_activity_tracker\Plugin\ActivityProcessorBase; +use Drupal\entity_activity_tracker\QueueActivityItem; /** * Sets activity when entity is created. @@ -90,20 +91,7 @@ public function submitConfigurationForm(array &$form, FormStateInterface $form_s * {@inheritdoc} */ public function getConfigField() { - return ($this->configuration['activity_existing_enabler']) ? 'activity_existing' : 'activity_creation'; - } - - /** - * {@inheritdoc} - */ - public function processActivity($event) { - $entity = $event->getEntity(); - $this->activityRecordStorage->applyActivity( - $entity->getEntityTypeId(), - $entity->bundle(), - $entity->id(), - $this->configuration['activity_creation'] - ); + return 'activity_creation'; } /** @@ -124,10 +112,13 @@ protected function getExistingEntities() { return $query->execute(); } + /** + * Get existing entities to be credited. + */ public function getExistingEntitiesToBeCredited() { $items = []; foreach ($this->getExistingEntities() as $entity_id) { - $items[] = $this->getActiveRecordItem($entity_id, $this->configuration[$this->getConfigField()]); + $items[] = $this->getActiveRecordItem($entity_id, $this->configuration['activity_existing']); } return $items; diff --git a/src/Plugin/ActivityProcessor/EntityDecay.php b/src/Plugin/ActivityProcessor/EntityDecay.php index 8eb4083..dd6fc62 100644 --- a/src/Plugin/ActivityProcessor/EntityDecay.php +++ b/src/Plugin/ActivityProcessor/EntityDecay.php @@ -2,10 +2,10 @@ namespace Drupal\entity_activity_tracker\Plugin\ActivityProcessor; -use Drupal\entity_activity_tracker\Plugin\ActivityProcessorBase; use Drupal\Core\Form\FormStateInterface; use Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface; -use Drupal\hook_event_dispatcher\Event\EventInterface; +use Drupal\entity_activity_tracker\Plugin\ActivityProcessorBase; +use Drupal\entity_activity_tracker\QueueActivityItem; /** * Sets setting for nodes and preforms the activity process for nodes. @@ -112,14 +112,14 @@ public function getConfigField() { /** * {@inheritdoc} */ - public function canProcess(EventInterface $event) { - return $this->getEvent() == $event->getDispatcherType(); + public function canProcess(QueueActivityItem $queue_activity_item) { + return $this->getEvent() == $queue_activity_item->getEventType(); } /** * {@inheritdoc} */ - public function processActivity($event) { + public function processActivity(QueueActivityItem $queue_activity_item) { $records = $this->recordsToDecay($this->tracker); switch ($this->configuration['decay_type']) { diff --git a/src/Plugin/ActivityProcessor/EntityEdit.php b/src/Plugin/ActivityProcessor/EntityEdit.php index 1f469f9..3a0fe2a 100644 --- a/src/Plugin/ActivityProcessor/EntityEdit.php +++ b/src/Plugin/ActivityProcessor/EntityEdit.php @@ -2,8 +2,9 @@ namespace Drupal\entity_activity_tracker\Plugin\ActivityProcessor; -use Drupal\entity_activity_tracker\Plugin\ActivityProcessorBase; use Drupal\Core\Form\FormStateInterface; +use Drupal\entity_activity_tracker\Plugin\ActivityProcessorBase; +use Drupal\entity_activity_tracker\QueueActivityItem; /** * Sets activity when entity is edited. @@ -74,17 +75,4 @@ public function getConfigField() { return 'activity_edit'; } - /** - * {@inheritdoc} - */ - public function processActivity($event) { - $entity = $event->getEntity(); - $this->activityRecordStorage->applyActivity( - $entity->getEntityTypeId(), - $entity->bundle(), - $entity->id(), - $this->configuration[$this->getConfigField()] - ); - } - } diff --git a/src/Plugin/ActivityProcessor/EntityView.php b/src/Plugin/ActivityProcessor/EntityView.php new file mode 100644 index 0000000..ef0bf00 --- /dev/null +++ b/src/Plugin/ActivityProcessor/EntityView.php @@ -0,0 +1,78 @@ + 10, + ]; + } + + /** + * {@inheritdoc} + */ + public function buildConfigurationForm(array $form, FormStateInterface $form_state) { + + $form['activity_view'] = [ + '#type' => 'number', + '#title' => $this->t('Activity on View'), + '#min' => 1, + '#default_value' => $this->getConfiguration()['activity_view'], + '#description' => $this->t('The activity value.'), + '#required' => TRUE, + ]; + + return $form; + } + + /** + * {@inheritdoc} + */ + public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { + $this->configuration['activity_view'] = $form_state->getValue('activity_view'); + } + + /** + * {@inheritdoc} + */ + public function getSummary() { + return $this->t('@plugin_name:
Activity on view: @activity_view
', [ + '@plugin_name' => $this->pluginDefinition['label']->render(), + '@activity_view' => $this->configuration['activity_view'], + ]); + } + + /** + * {@inheritdoc} + */ + public function getConfigField() { + return 'activity_view'; + } + +} diff --git a/src/Plugin/ActivityProcessorBase.php b/src/Plugin/ActivityProcessorBase.php index e53091a..536e170 100644 --- a/src/Plugin/ActivityProcessorBase.php +++ b/src/Plugin/ActivityProcessorBase.php @@ -3,14 +3,15 @@ namespace Drupal\entity_activity_tracker\Plugin; use Drupal\Component\Plugin\PluginBase; +use Drupal\Core\Cache\Cache; use Drupal\Core\DependencyInjection\DependencySerializationTrait; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Form\FormStateInterface; -use Drupal\entity_activity_tracker\ActivityRecordStorageInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; +use Drupal\entity_activity_tracker\ActivityRecordStorageInterface; use Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface; +use Drupal\entity_activity_tracker\QueueActivityItem; use Symfony\Component\DependencyInjection\ContainerInterface; -use Drupal\hook_event_dispatcher\Event\EventInterface; /** * Base class for Activity processor plugins. @@ -51,6 +52,7 @@ public function __construct( ActivityRecordStorageInterface $activity_record_storage, EntityTypeManagerInterface $entity_type_manager ) { + parent::__construct($configuration, $plugin_id, $plugin_definition); $this->activityRecordStorage = $activity_record_storage; $this->entityTypeManager = $entity_type_manager; @@ -70,6 +72,12 @@ public static function create(ContainerInterface $container, array $configuratio ); } + /** + * Set tracker. + * + * @param \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface $tracker + * Tracker. + */ public function setTracker(EntityActivityTrackerInterface $tracker) { $this->tracker = $tracker; } @@ -93,8 +101,15 @@ public function getSummary() { /** * {@inheritdoc} */ - public function processActivity(EventInterface $event) { - // code... + public function processActivity(QueueActivityItem $queue_activity_item) { + $entity = $queue_activity_item->getEntity(); + $this->activityRecordStorage->applyActivity( + $entity->getEntityTypeId(), + $entity->bundle(), + $entity->id(), + $this->configuration[$this->getConfigField()] + ); + $this->cleanCache($queue_activity_item); } /** @@ -107,12 +122,12 @@ public function validateConfigurationForm(array &$form, FormStateInterface $form /** * {@inheritdoc} */ - public function canProcess(EventInterface $event) { - if ($this->getEvent() != $event->getDispatcherType()) { + public function canProcess(QueueActivityItem $queue_activity_item) { + if ($this->getEvent() != $queue_activity_item->getEventType()) { return FALSE; } - $entity = $event->getEntity(); + $entity = $queue_activity_item->getEntity(); // Entity doesn't have any relations and the current tracker handles it. return empty($this->getPluginDefinition()['target_entity_type']) && $entity->getEntityTypeId() == $this->tracker->getTargetEntityType() && $entity->bundle() == $this->tracker->getTargetEntityBundle(); } @@ -155,11 +170,11 @@ public function isAccessible() { * Entity data to be credited. */ public function getExistingEntitiesToBeCredited() { - return []; + return []; } /** - * Get entity data array for crediting + * Get entity data array for crediting. * * @param int $entity_id * Entity id. @@ -188,4 +203,14 @@ public function getEvent() { return $this->getPluginDefinition()['event']; } + public function cleanCache(QueueActivityItem $queue_activity_item) { + $entity = $queue_activity_item->getEntity(); + if ($entity) { + Cache::invalidateTags([ + "{$entity->getEntityTypeId()}:{$entity->id()}", + "{$entity->getEntityTypeId()}_list", + ]); + } + } + } diff --git a/src/Plugin/ActivityProcessorCollection.php b/src/Plugin/ActivityProcessorCollection.php index f87bf03..3a6d766 100644 --- a/src/Plugin/ActivityProcessorCollection.php +++ b/src/Plugin/ActivityProcessorCollection.php @@ -26,10 +26,12 @@ class ActivityProcessorCollection extends DefaultLazyPluginCollection { * @param array $configurations * (optional) An associative array containing the initial configuration for * each plugin in the collection, keyed by plugin instance ID. + * @param \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface $tracker + * Tracker. */ public function __construct( PluginManagerInterface $manager, - array $configurations = [], + array $configurations, EntityActivityTrackerInterface $tracker ) { parent::__construct($manager, $configurations); diff --git a/src/Plugin/ActivityProcessorCreditRelatedBase.php b/src/Plugin/ActivityProcessorCreditRelatedBase.php index dea24e0..e400462 100644 --- a/src/Plugin/ActivityProcessorCreditRelatedBase.php +++ b/src/Plugin/ActivityProcessorCreditRelatedBase.php @@ -3,6 +3,7 @@ namespace Drupal\entity_activity_tracker\Plugin; use Drupal\Core\Entity\ContentEntityInterface; +use Drupal\entity_activity_tracker\QueueActivityItem; /** * Base class for Activity processor plugins. @@ -12,12 +13,12 @@ abstract class ActivityProcessorCreditRelatedBase extends ActivityProcessorBase /** * {@inheritdoc} */ - public function canProcess($event) { - if ($this->getEvent() != $event->getDispatcherType()) { + public function canProcess(QueueActivityItem $queue_activity_item) { + if ($this->getEvent() != $queue_activity_item->getEventType()) { return FALSE; } - $entity = $event->getEntity(); + $entity = $queue_activity_item->getEntity(); // Plugin has related entity. return !empty($this->getPluginDefinition()['target_entity_type']) && $this->getPluginDefinition()['target_entity_type'] == $entity->getEntityTypeId(); @@ -26,7 +27,7 @@ public function canProcess($event) { /** * Get entities related to the give entity. * - * @param ContentEntityInterface $entity + * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The entity attached to event. * * @return array @@ -39,8 +40,8 @@ protected function getRelatedEntities(ContentEntityInterface $entity) { /** * {@inheritdoc} */ - public function processActivity($event) { - $entity = $event->getEntity(); + public function processActivity(QueueActivityItem $queue_activity_item) { + $entity = $queue_activity_item->getEntity(); $related_entities = $this->getRelatedEntities($entity); foreach ($related_entities as $related_entity) { diff --git a/src/Plugin/ActivityProcessorInterface.php b/src/Plugin/ActivityProcessorInterface.php index e195e40..87e82b3 100644 --- a/src/Plugin/ActivityProcessorInterface.php +++ b/src/Plugin/ActivityProcessorInterface.php @@ -2,12 +2,11 @@ namespace Drupal\entity_activity_tracker\Plugin; -use Drupal\Component\Plugin\PluginInspectionInterface; use Drupal\Component\Plugin\ConfigurableInterface; -use Drupal\Core\Entity\EntityInterface; -use Drupal\Core\Plugin\PluginFormInterface; +use Drupal\Component\Plugin\PluginInspectionInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; -use Drupal\hook_event_dispatcher\Event\EventInterface; +use Drupal\Core\Plugin\PluginFormInterface; +use Drupal\entity_activity_tracker\QueueActivityItem; /** * Defines an interface for Activity processor plugins. @@ -20,14 +19,14 @@ interface ActivityProcessorInterface extends PluginInspectionInterface, Configur public function getConfigField(); /** - * Process activity of an event. + * Process activity of an item. */ - public function processActivity(EventInterface $event); + public function processActivity(QueueActivityItem $queue_activity_item); /** - * Checks if we can process an event. + * Checks if we can process an item. */ - public function canProcess(EventInterface $entity); + public function canProcess(QueueActivityItem $queue_activity_item); /** * Checks if the plugin accessible. diff --git a/src/Plugin/ActivityProcessorManager.php b/src/Plugin/ActivityProcessorManager.php index 758f966..1e155b7 100644 --- a/src/Plugin/ActivityProcessorManager.php +++ b/src/Plugin/ActivityProcessorManager.php @@ -2,9 +2,9 @@ namespace Drupal\entity_activity_tracker\Plugin; -use Drupal\Core\Plugin\DefaultPluginManager; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Extension\ModuleHandlerInterface; +use Drupal\Core\Plugin\DefaultPluginManager; /** * Provides the Activity processor plugin manager. diff --git a/src/Plugin/QueueWorker/ActivityProcessorQueue.php b/src/Plugin/QueueWorker/ActivityProcessorQueue.php index 01944d8..bdab40a 100644 --- a/src/Plugin/QueueWorker/ActivityProcessorQueue.php +++ b/src/Plugin/QueueWorker/ActivityProcessorQueue.php @@ -16,13 +16,13 @@ class ActivityProcessorQueue extends ActivityQueueWorkerBase { /** * {@inheritdoc} */ - public function processItem($event) { + public function processItem($queue_activity_item) { $trackers = $this->trackerLoader->getAll(); foreach ($trackers as $tracker) { $plugins = $tracker->getEnabledProcessorsPlugins(); foreach ($plugins as $plugin_id => $plugin) { - if ($plugin->canProcess($event)) { - $plugin->processActivity($event); + if ($plugin->canProcess($queue_activity_item)) { + $plugin->processActivity($queue_activity_item); $this->logInfo("$plugin_id plugin processed"); } } diff --git a/src/Plugin/QueueWorker/ActivityQueueWorkerBase.php b/src/Plugin/QueueWorker/ActivityQueueWorkerBase.php index b9d144a..5f85d12 100644 --- a/src/Plugin/QueueWorker/ActivityQueueWorkerBase.php +++ b/src/Plugin/QueueWorker/ActivityQueueWorkerBase.php @@ -4,10 +4,10 @@ use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Drupal\Core\Queue\QueueWorkerBase; use Drupal\entity_activity_tracker\TrackerLoader; use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; -use Drupal\Core\Queue\QueueWorkerBase; /** * Provides a base implementation for a QueueWorker plugin. diff --git a/src/Plugin/QueueWorker/CreditItemProcessorQueue.php b/src/Plugin/QueueWorker/CreditItemProcessorQueue.php index 2537482..8652e41 100644 --- a/src/Plugin/QueueWorker/CreditItemProcessorQueue.php +++ b/src/Plugin/QueueWorker/CreditItemProcessorQueue.php @@ -2,6 +2,7 @@ namespace Drupal\entity_activity_tracker\Plugin\QueueWorker; +use Drupal\Core\Cache\Cache; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Queue\QueueFactory; use Drupal\entity_activity_tracker\ActivityRecordStorageInterface; @@ -27,7 +28,6 @@ class CreditItemProcessorQueue extends ActivityQueueWorkerBase { */ protected $activityRecordStorage; - /** * The queue service. * @@ -52,6 +52,8 @@ class CreditItemProcessorQueue extends ActivityQueueWorkerBase { * Tracker loader. * @param \Drupal\Core\Queue\QueueFactory $queue * Queue manager. + * @param \Drupal\entity_activity_tracker\ActivityRecordStorageInterface $activity_record_storage + * Activity record storage. */ public function __construct( array $configuration, @@ -105,6 +107,10 @@ public function processItem($items) { $item['entity_id'], $item['activity'] ); + Cache::invalidateTags([ + "{$item['entity_type']}:{$item['entity_id']}", + "{$item['entity_type']}_list", + ]); unset($items[$id]); $i++; } diff --git a/src/Plugin/QueueWorker/TrackerProcessorQueue.php b/src/Plugin/QueueWorker/TrackerProcessorQueue.php index 931d0b1..3af3922 100644 --- a/src/Plugin/QueueWorker/TrackerProcessorQueue.php +++ b/src/Plugin/QueueWorker/TrackerProcessorQueue.php @@ -75,9 +75,9 @@ public static function create(ContainerInterface $container, array $configuratio /** * {@inheritdoc} */ - public function processItem($event) { + public function processItem($queue_activity_item) { - $tracker = $event->getEntity(); + $tracker = $queue_activity_item->getEntity(); $plugins = $tracker->getEnabledProcessorsPlugins(); // We get existing entities for each plugin and activity points diff --git a/src/Plugin/views/field/TrackedEntity.php b/src/Plugin/views/field/TrackedEntity.php index e3069ad..0b5c0e6 100644 --- a/src/Plugin/views/field/TrackedEntity.php +++ b/src/Plugin/views/field/TrackedEntity.php @@ -2,12 +2,12 @@ namespace Drupal\entity_activity_tracker\Plugin\views\field; +use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Drupal\entity_activity_tracker\ActivityRecordStorageInterface; use Drupal\views\Plugin\views\field\FieldPluginBase; use Drupal\views\ResultRow; -use Drupal\Core\Plugin\ContainerFactoryPluginInterface; -use Drupal\Core\Entity\EntityTypeManagerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; -use Drupal\entity_activity_tracker\ActivityRecordStorageInterface; /** * A handler to provide a field that is completely custom by the administrator. @@ -50,8 +50,7 @@ public function __construct( array $configuration, $plugin_id, $plugin_definition, - EntityTypeManagerInterface - $entity_type_manager, + EntityTypeManagerInterface $entity_type_manager, ActivityRecordStorageInterface $activity_record_storage ) { parent::__construct($configuration, $plugin_id, $plugin_definition); @@ -112,7 +111,11 @@ public function render(ResultRow $values) { $entity_storage = $this->entityTypeManager->getStorage($activity_record->getEntityType()); $tracked_entity = $entity_storage->load($activity_record->getEntityId()); - return $tracked_entity->toLink()->toString(); + if ($tracked_entity) { + return $tracked_entity->toLink()->toString(); + } + + return NULL; } } diff --git a/src/QueueActivityItem.php b/src/QueueActivityItem.php new file mode 100644 index 0000000..1b9b9a7 --- /dev/null +++ b/src/QueueActivityItem.php @@ -0,0 +1,61 @@ +eventType = $event_type; + } + + /** + * Get entity. + * + * @return \Drupal\Core\Entity\EntityInterface + * Entity. + */ + public function getEntity() { + return $this->entity; + } + + /** + * Set entity. + * + * @param \Drupal\Core\Entity\EntityInterface $entity + * Entity. + */ + public function setEntity($entity) { + $this->entity = $entity; + } + + /** + * Get event type. + * + * @return string + * Eent type. + */ + public function getEventType() { + return $this->eventType; + } + +} diff --git a/src/TrackerLoader.php b/src/TrackerLoader.php index 7a15e09..7b267e6 100644 --- a/src/TrackerLoader.php +++ b/src/TrackerLoader.php @@ -52,7 +52,7 @@ public function getTrackerByEntity(ContentEntityInterface $entity) { } /** - * Get tracker by it's bundle info. + * Get tracker by it is bundle info. * * @param string $entity_type * Entity type. @@ -60,6 +60,7 @@ public function getTrackerByEntity(ContentEntityInterface $entity) { * Entity bundle. * * @return array|\Drupal\Core\Entity\EntityInterface[] + * Trackers. */ public function getTrackerByEntityBundle($entity_type, $entity_bundle) { $key = "{$entity_type}-{$entity_bundle}"; @@ -90,7 +91,7 @@ public function getAll() { /** * Check if exists EntityActivityTracker for given entity. * - * @param ContentEntityInterface $entity + * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The entity to check if it has a tracker. * * @return bool @@ -103,7 +104,7 @@ public function hasTracker(ContentEntityInterface $entity) { /** * Get tracker canonical url given tracked entity. * - * @param ContentEntityInterface $entity + * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The tracked entity. * * @return \Drupal\Core\Url diff --git a/tests/src/Kernel/EntityActivityTrackerBasicPluginsTest.php b/tests/src/Kernel/EntityActivityTrackerBasicPluginsTest.php index 60af106..0179143 100755 --- a/tests/src/Kernel/EntityActivityTrackerBasicPluginsTest.php +++ b/tests/src/Kernel/EntityActivityTrackerBasicPluginsTest.php @@ -2,7 +2,6 @@ namespace Drupal\Tests\entity_activity_tracker\Kernel; - use Drupal\entity_activity_tracker\Plugin\ActivityProcessor\EntityDecay; /** @@ -25,7 +24,8 @@ class EntityActivityTrackerBasicPluginsTest extends EntityActivityTrackerTestBas ]; /** - * Create a tracker for node type article. + * Create a tracker for node type article. + * * @param bool $run_cron * Run cron after. * @@ -33,20 +33,21 @@ class EntityActivityTrackerBasicPluginsTest extends EntityActivityTrackerTestBas * Create tracker for an article. */ protected function createTrackerForNodeArticle($run_cron) { - // @TODO: refactor hardcoded values. return $this->createTracker('node', 'article', [ 'entity_create' => [ 'enabled' => 1, 'activity_creation' => 100, 'activity_existing' => 50, 'activity_existing_enabler' => 1, - ] + ], ], $run_cron); } /** - * @param $run_cron - * Run cron after + * Create a tracker with a decay plugin. + * + * @param bool $run_cron + * Run cron after. * @param int $entity_create_activity_point * Create activity points. * @param int $entity_decay_activity_point @@ -58,7 +59,6 @@ protected function createTrackerForNodeArticle($run_cron) { * Tracker. */ protected function createTrackerWithDecayPlugin($run_cron, $entity_create_activity_point, $entity_decay_activity_point, $decay_type) { - // @TODO: refactor hardcoded values. return $this->createTracker('node', 'article', [ 'entity_create' => [ 'enabled' => 1, @@ -76,7 +76,9 @@ protected function createTrackerWithDecayPlugin($run_cron, $entity_create_activi } /** - * Test when we create tracker we want to apply activity points to existing entities. + * Test when we create tracker. + * + * We want to apply activity points to existing entities. */ public function testTrackerCreationExistingEntity() { $article = $this->createNode('article', TRUE); @@ -94,8 +96,8 @@ public function testEntityCreation() { $this->createTrackerForNodeArticle(TRUE); $article = $this->createNode('article'); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($article); - $this->assertTrue( !empty($activity_record)); - // The case when we apply + $this->assertTrue(!empty($activity_record)); + // The case when we apply. $this->assertEquals(100, $activity_record->getActivityValue()); } @@ -161,7 +163,7 @@ public function testNotTrackedBundles() { $this->createTrackerForNodeArticle(TRUE); $activity_record = $this->activityRecordStorage->getActivityRecordByEntity($page); - $this->assertTrue( empty($activity_record)); + $this->assertTrue(empty($activity_record)); } /** diff --git a/tests/src/Kernel/EntityActivityTrackerTestBase.php b/tests/src/Kernel/EntityActivityTrackerTestBase.php index 7aab6d4..5f411a5 100755 --- a/tests/src/Kernel/EntityActivityTrackerTestBase.php +++ b/tests/src/Kernel/EntityActivityTrackerTestBase.php @@ -76,7 +76,7 @@ protected function setUp():void { * Entity type. * @param array $values * Values. - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\Core\Entity\EntityInterface @@ -104,7 +104,7 @@ protected function createEntity($entity_type, array $values, $run_cron) { * Bundle. * @param array $processors * List of processors configuration. - * @param $run_cron + * @param bool $run_cron * Run cron after. * * @return \Drupal\entity_activity_tracker\Entity\EntityActivityTrackerInterface @@ -125,7 +125,7 @@ protected function createTracker($entity_type, $bundle, array $processors, $run_ * * @param string $type * Node type. - * @param $run_cron + * @param bool $run_cron * Run cron service after. * * @return \Drupal\node\NodeInterface @@ -143,8 +143,8 @@ protected function createNode($type, $run_cron = TRUE) { /** * Creates a node type. * - * @param array $values - * (optional) The values used to create the entity. + * @param array $type + * Node type. * * @return \Drupal\node\Entity\NodeType * The created node type entity. @@ -159,7 +159,7 @@ protected function createNodeType($type) { /** * Removes entity. * - * @param EntityInterface $entity + * @param \Drupal\Core\Entity\EntityInterface $entity * Entity to be removed. */ protected function removeEntity(EntityInterface $entity) { @@ -188,7 +188,7 @@ protected function getPluginActivityPoints(EntityActivityTrackerInterface $track * * @param \Drupal\node\NodeInterface $node * Node entity. - * @param $run_cron + * @param bool $run_cron * Run cron service after. * * @return \Drupal\comment\CommentInterface