Browse Source

Issue 643 (#63)

* First pass with the flamethrower

* Updates after testing.  Rules

* Updates from testing on fresh install

* Forgot these
pull/756/head
dannylamb 8 years ago committed by Nick Ruest
parent
commit
07f69a80da
  1. 13
      config/install/core.entity_view_mode.fedora_resource.teaser.yml
  2. 3
      config/install/field.field.media.tn.field_height.yml
  3. 4
      config/install/field.storage.node.field_description.yml
  4. 6
      config/install/field.storage.node.field_memberof.yml
  5. 4
      config/install/field.storage.node.field_obj.yml
  6. 4
      config/install/field.storage.node.field_tn.yml
  7. 26
      config/install/rest.resource.entity.fedora_resource.yml
  8. 17
      config/install/rest.resource.entity.media.yml
  9. 27
      config/install/rules.reaction.broadcast_content_create_event.yml
  10. 27
      config/install/rules.reaction.broadcast_content_delete_event.yml
  11. 27
      config/install/rules.reaction.broadcast_content_update_event.yml
  12. 16
      config/install/rules.reaction.broadcast_media_create_event.yml
  13. 16
      config/install/rules.reaction.broadcast_media_delete_event.yml
  14. 16
      config/install/rules.reaction.broadcast_media_update_event.yml
  15. 169
      config/install/views.view.fedora_entities_reference.yml
  16. 216
      config/install/views.view.membership_view.yml
  17. 24
      config/schema/fedora_resource_type.schema.yml
  18. 71
      fedora_resource.page.inc
  19. 18
      islandora.install
  20. 10
      islandora.links.action.yml
  21. 8
      islandora.links.menu.yml
  22. 21
      islandora.links.task.yml
  23. 40
      islandora.module
  24. 26
      islandora.permissions.yml
  25. 10
      islandora.routing.yml
  26. 119
      src/Controller/FedoraResourceAddController.php
  27. 16
      src/Controller/JsonLdContextController.php
  28. 465
      src/Entity/FedoraResource.php
  29. 57
      src/Entity/FedoraResourceType.php
  30. 31
      src/Entity/FedoraResourceViewsData.php
  31. 48
      src/FedoraResourceAccessControlHandler.php
  32. 184
      src/FedoraResourceHtmlRouteProvider.php
  33. 119
      src/FedoraResourceInterface.php
  34. 48
      src/FedoraResourceListBuilder.php
  35. 97
      src/FedoraResourceTypeHtmlRouteProvider.php
  36. 13
      src/FedoraResourceTypeInterface.php
  37. 32
      src/FedoraResourceTypeListBuilder.php
  38. 18
      src/FedoraResourceViewBuilder.php
  39. 15
      src/Form/FedoraResourceDeleteForm.php
  40. 287
      src/Form/FedoraResourceEntityInlineForm.php
  41. 48
      src/Form/FedoraResourceForm.php
  42. 55
      src/Form/FedoraResourceSettingsForm.php
  43. 53
      src/Form/FedoraResourceTypeDeleteForm.php
  44. 67
      src/Form/FedoraResourceTypeForm.php
  45. 839
      src/Plugin/Search/FedoraEntitySearch.php
  46. 130
      src/Plugin/views/wizard/FedoraResource.php
  47. 36
      src/Tests/Web/JsonldContextGeneratorWebTest.php
  48. 23
      templates/fedora-resource-content-add-list.html.twig
  49. 22
      templates/fedora_resource.html.twig
  50. 92
      tests/src/Kernel/DeleteFedoraResourceWithParentsTest.php
  51. 17
      tests/src/Kernel/EventGeneratorTestBase.php
  52. 43
      tests/src/Kernel/FedoraContentTypeCreationTrait.php
  53. 134
      tests/src/Kernel/FedoraResourceParentTest.php
  54. 3
      tests/src/Kernel/IslandoraKernelTestBase.php
  55. 23
      tests/src/Kernel/VersionCounterTest.php

13
config/install/core.entity_view_mode.fedora_resource.teaser.yml

@ -1,13 +0,0 @@
uuid: 0efc20d3-0bd6-4606-842f-b87548de1924
langcode: en
status: true
dependencies:
enforced:
module:
- islandora
_core:
default_config_hash: PnOwgzHIcT0m2y9dN2B5D7og29JXDCm4dCqb1pKUWek
id: fedora_resource.teaser
label: Teaser
targetEntityType: fedora_resource
cache: true

3
config/install/field.field.media.tn.field_height.yml

@ -5,6 +5,9 @@ dependencies:
config:
- field.storage.media.field_height
- media_entity.bundle.tn
enforced:
module:
- islandora
id: media.tn.field_height
field_name: field_height
entity_type: media

4
config/install/field.storage.fedora_resource.field_description.yml → config/install/field.storage.node.field_description.yml

@ -6,9 +6,9 @@ dependencies:
enforced:
module:
- islandora
id: fedora_resource.field_description
id: node.field_description
field_name: field_description
entity_type: fedora_resource
entity_type: node
type: string_long
settings:
case_sensitive: false

6
config/install/field.storage.fedora_resource.field_memberof.yml → config/install/field.storage.node.field_memberof.yml

@ -6,12 +6,12 @@ dependencies:
enforced:
module:
- islandora
id: fedora_resource.field_memberof
id: node.field_memberof
field_name: field_memberof
entity_type: fedora_resource
entity_type: node
type: entity_reference
settings:
target_type: fedora_resource
target_type: node
module: core
locked: false
cardinality: 1

4
config/install/field.storage.fedora_resource.field_obj.yml → config/install/field.storage.node.field_obj.yml

@ -8,9 +8,9 @@ dependencies:
module:
- islandora
- media_entity
id: fedora_resource.field_obj
id: node.field_obj
field_name: field_obj
entity_type: fedora_resource
entity_type: node
type: entity_reference
settings:
target_type: media

4
config/install/field.storage.fedora_resource.field_tn.yml → config/install/field.storage.node.field_tn.yml

@ -8,9 +8,9 @@ dependencies:
enforced:
module:
- islandora
id: fedora_resource.field_tn
id: node.field_tn
field_name: field_tn
entity_type: fedora_resource
entity_type: node
type: entity_reference
settings:
target_type: media

26
config/install/rest.resource.entity.fedora_resource.yml

@ -1,26 +0,0 @@
uuid: f29f59d6-ed21-46cf-84e2-42141255b0de
langcode: en
status: true
dependencies:
enforced:
module:
- islandora
module:
- islandora
- jsonld
- jwt
- serialization
- user
_core:
default_config_hash: ByaS2KNrlkozt1uLxjOhK6_GNxwV3iIhvXHNqdMZGo8
id: entity.fedora_resource
plugin_id: 'entity:fedora_resource'
granularity: method
configuration:
GET:
supported_formats:
- jsonld
- json
supported_auth:
- jwt_auth
- cookie

17
config/install/rest.resource.entity.media.yml

@ -1,24 +1,27 @@
uuid: 08836232-8f53-422b-97bd-4394a9660480
uuid: bf3d7c56-77d9-4154-a7b8-bb77c7188569
langcode: en
status: true
dependencies:
module:
- basic_auth
- hal
- jsonld
- jwt
- media_entity
- serialization
- user
enforced:
module:
- islandora
id: entity.media
plugin_id: 'entity:media'
granularity: method
granularity: resource
configuration:
GET:
supported_formats:
methods:
- GET
formats:
- hal_json
- jsonld
- json
supported_auth:
authentication:
- basic_auth
- jwt_auth
- cookie

27
config/install/rules.reaction.broadcast_create_event.yml → config/install/rules.reaction.broadcast_content_create_event.yml

@ -1,48 +1,43 @@
uuid: 3ef878c1-3187-4141-aba1-2aac5acc9366
uuid: b8d1db0c-be8f-47a7-889f-ac710db2e18a
langcode: en
status: true
dependencies:
module:
- islandora
- rules
enforced:
module:
- islandora
_core:
default_config_hash: EKVRKXObBdrm-lGcG3RPpF8sg0tZSZbZx00lkzm42_E
id: broadcast_create_event
label: 'Broadcast Create Event'
id: broadcast_content_create_event
label: 'Broadcast Content Create Event'
events:
-
event_name: 'rules_entity_insert:fedora_resource'
description: 'Broadcasts a ''Create'' event when a user creates a new FedoraResource.'
event_name: 'rules_entity_insert:node'
description: 'Broadcasts an AS2 event to a message broker when Content is created.'
tags:
- ''
config_version: '3'
expression:
id: rules_rule
uuid: d25688b0-eef1-46b0-acf4-98a6d1ccd76a
uuid: 40cabb74-fcc7-4498-90f9-3a4ec71b3710
conditions:
id: rules_and
uuid: 6648629a-0b52-4352-bb85-df2cbafb7db2
uuid: 8e0d7b29-15f4-448d-b79a-d85ef97d274e
conditions: { }
actions:
id: rules_action_set
uuid: 957db51c-d055-4350-8caa-4ad773172e87
uuid: 0f832259-2aa1-45a4-83df-d9e0ff4c7edd
actions:
-
id: rules_action
uuid: d483f5bc-fd36-4d7c-baa4-66234b438d1a
uuid: 922264b9-3db1-42eb-9e01-e781a58a3695
context_values: { }
context_mapping:
entity: fedora_resource
entity: node
user: '@user.current_user_context:current_user'
context_processors: { }
provides_mapping: { }
action_id: islandora_create_event_generator
-
id: rules_action
uuid: 2afa7216-91bb-49a3-a567-e504ba8f95e1
uuid: 0e953790-c751-4de8-99b3-c729ba1e09e3
context_values:
recipients:
- "activemq:queue:islandora-indexing-fcrepo-create\r"

27
config/install/rules.reaction.broadcast_delete_event.yml → config/install/rules.reaction.broadcast_content_delete_event.yml

@ -1,48 +1,43 @@
uuid: 16c10c0c-68a7-4b75-ab8f-ab1778d7c2e2
uuid: 752003c1-8d98-4d33-b6d3-2bdde52e77bf
langcode: en
status: true
dependencies:
module:
- islandora
- rules
enforced:
module:
- islandora
_core:
default_config_hash: 79mBUbR_0wDo3oT4vWjuFgGPic_hghVkQ0yiYMuxLns
id: broadcast_delete_event
label: 'Broadcast Delete Event'
id: broadcast_content_delete_event
label: 'Broadcast Content Delete Event'
events:
-
event_name: 'rules_entity_delete:fedora_resource'
description: 'Broadcasts a ''Delete'' event when a user deletes a FedoraResource.'
event_name: 'rules_entity_delete:node'
description: 'Broadcasts an AS2 event to a message broker when Content is deleted.'
tags:
- ''
config_version: '3'
expression:
id: rules_rule
uuid: dd0ffd15-c6b4-4578-8b54-9c9debae0216
uuid: b5ca11c1-f80c-4dce-a9f7-9d5db0fec971
conditions:
id: rules_and
uuid: 9c50dd1f-ec9a-4cd8-9d18-27c860815a1c
uuid: ede4e2b7-ce4c-4a9d-a5ff-a18a248ccd4c
conditions: { }
actions:
id: rules_action_set
uuid: 7f1f1fc6-d5d2-450b-ba14-225e8e56448f
uuid: 7c96bc08-7b7e-499d-8535-a2c735f6b98b
actions:
-
id: rules_action
uuid: 7ebcda8c-3626-4bff-a536-60caf9f46708
uuid: 36647c5b-3355-4d4b-8550-5b0170b98ad1
context_values: { }
context_mapping:
entity: fedora_resource
entity: node
user: '@user.current_user_context:current_user'
context_processors: { }
provides_mapping: { }
action_id: islandora_delete_event_generator
-
id: rules_action
uuid: 53942d65-7567-4b6b-9b43-4d67079651f6
uuid: 9257b59c-466c-43d7-8690-62dd87a053eb
context_values:
recipients:
- "activemq:queue:islandora-indexing-fcrepo-delete\r"

27
config/install/rules.reaction.broadcast_update_event.yml → config/install/rules.reaction.broadcast_content_update_event.yml

@ -1,48 +1,43 @@
uuid: 3bfa9b33-b0a7-437e-a949-e50178a702fe
uuid: 9eeb9a6a-d3ba-41b3-9f1f-68bd016fe8b1
langcode: en
status: true
dependencies:
module:
- islandora
- rules
enforced:
module:
- islandora
_core:
default_config_hash: XX87LaQzcIVbzZTzUR4HBgeZKCzKOMJzVCTJYgmg47k
id: broadcast_update_event
label: 'Broadcast Update Event'
id: broadcast_content_update_event
label: 'Broadcast Content Update Event'
events:
-
event_name: 'rules_entity_update:fedora_resource'
description: 'Broadcasts a ''Update'' event when a user updates a FedoraResource.'
event_name: 'rules_entity_update:node'
description: 'Broadcasts an AS2 event to a message broker when Content is updated.'
tags:
- ''
config_version: '3'
expression:
id: rules_rule
uuid: 55563628-5ea2-4459-989e-0ce573f50aaa
uuid: 55f8a158-3fe4-48bb-92f2-ba53630d56f3
conditions:
id: rules_and
uuid: 8113ab9f-7af6-4315-8701-60812bb86190
uuid: 8269d20f-cb56-4399-8c87-17eb64bfe5eb
conditions: { }
actions:
id: rules_action_set
uuid: 78330180-141b-404e-8bf3-b7c9d8dcc748
uuid: 567aca08-456f-449e-a91b-b17a21366bdf
actions:
-
id: rules_action
uuid: 86a6f157-8d0c-4b3c-bd8e-d4c3ce4794a7
uuid: ee51523e-3bba-43a5-95ce-e998fb3392d3
context_values: { }
context_mapping:
entity: fedora_resource
entity: node
user: '@user.current_user_context:current_user'
context_processors: { }
provides_mapping: { }
action_id: islandora_update_event_generator
-
id: rules_action
uuid: 40aa4a03-ad36-45bf-9584-ede3b9b3e5c9
uuid: 7b9cf7be-40e4-4490-ae6f-07a84eb112c4
context_values:
recipients:
- "activemq:queue:islandora-indexing-fcrepo-update\r"

16
config/install/rules.reaction.broadcast_media_create_event.yml

@ -1,35 +1,33 @@
uuid: c4447a0b-a2a8-4f32-947b-fbe1094632d5
uuid: 4474df44-01ee-4abf-84f9-9aa41d787d27
langcode: en
status: true
dependencies:
enforced:
module:
- islandora
_core:
default_config_hash: mRt_MC0dKA68qaoXI3WlnCg-ta5Wry0dLR2dpOqY4to
id: broadcast_media_create_event
label: 'Broadcast Media Create Event'
events:
-
event_name: 'rules_entity_insert:media'
description: 'Broadcasts a ''Create'' event when a user creates a new Media.'
description: 'Broadcasts an AS2 event to a message broker when Media is created.'
tags:
- ''
config_version: '3'
expression:
id: rules_rule
uuid: 3294a215-25d9-4bfe-9e84-745f381107c5
uuid: d4ba4cc1-3b18-400d-867f-1605d72d9717
conditions:
id: rules_and
uuid: 6dbe3930-7d39-4927-890e-4af4e8fb57fc
uuid: 9ccf9d29-89be-4b1d-8417-230e33f8fd6f
conditions: { }
actions:
id: rules_action_set
uuid: 470ed84d-b33f-4ff4-a584-481605bc826c
uuid: 47afb6b3-e39e-4c3a-af47-669e963353a2
actions:
-
id: rules_action
uuid: 59b35164-5e52-4664-afe1-86e8f3bda01d
uuid: dff4ebfb-84c5-4d0f-acf7-62e3edbab143
context_values: { }
context_mapping:
entity: media
@ -39,7 +37,7 @@ expression:
action_id: islandora_create_event_generator
-
id: rules_action
uuid: f7880d70-1411-4c60-a065-a7d187b604db
uuid: 6b0d07b3-048e-43ac-8a9f-2c5203f8080e
context_values:
recipients:
- "activemq:queue:islandora-indexing-triplestore\r"

16
config/install/rules.reaction.broadcast_media_delete_event.yml

@ -1,35 +1,33 @@
uuid: 33b8afa6-1507-4f04-acc9-5a18ca2b0ccc
uuid: 71df1b5d-2f04-42fa-a660-5375de9c6c51
langcode: en
status: true
dependencies:
enforced:
module:
- islandora
_core:
default_config_hash: Jejr-Hg2lX1o7mdUt_RBxW0xfzOKhoFbGGpepW_SoZg
id: broadcast_media_delete_event
label: 'Broadcast Media Delete Event'
events:
-
event_name: 'rules_entity_delete:media'
description: 'Broadcasts a ''Delete'' event when a user deletes a Media.'
description: 'Broadcasts an AS2 event to a message broker when Media is deleted.'
tags:
- ''
config_version: '3'
expression:
id: rules_rule
uuid: 40abb71f-da16-49c3-8646-19921e911b7e
uuid: c12184e7-8230-4bc7-b625-2a26b4a5a913
conditions:
id: rules_and
uuid: 34e4e2d6-f6be-4644-ba30-b434b7f2f82b
uuid: 5147d740-4e32-4935-8c30-f893e7c3f86f
conditions: { }
actions:
id: rules_action_set
uuid: 4032fcca-f4ab-471e-afa0-f53e2148848d
uuid: 4a023b99-1cf8-410a-a082-b0c0369a807d
actions:
-
id: rules_action
uuid: 8d9547b4-477d-4442-b8b6-2d677cf79d1d
uuid: 1fdc07dc-72ba-4666-abb8-8d79f29b67ff
context_values: { }
context_mapping:
entity: media
@ -39,7 +37,7 @@ expression:
action_id: islandora_delete_event_generator
-
id: rules_action
uuid: 371b1104-1aa6-4b3d-82cf-e27168e664ae
uuid: 75d0cf84-715b-4167-8ec2-92047a0bec56
context_values:
recipients:
- "activemq:queue:islandora-indexing-triplestore\r"

16
config/install/rules.reaction.broadcast_media_update_event.yml

@ -1,35 +1,33 @@
uuid: d58d3327-38d2-400b-91a0-3b00b3870121
uuid: d5d823ce-cfd0-4e9c-85c9-9090660d831e
langcode: en
status: true
dependencies:
enforced:
module:
- islandora
_core:
default_config_hash: qAkxtz6jH0on_W4QXhpGqZMFfgyATahnUKdynX9bl1g
id: broadcast_media_update_event
label: 'Broadcast Media Update Event'
events:
-
event_name: 'rules_entity_update:media'
description: 'Broadcasts an ''Update'' event when a user updates a Media.'
description: 'Broadcasts an AS2 event to a message broker when Media is updated.'
tags:
- ''
config_version: '3'
expression:
id: rules_rule
uuid: 9974766d-92df-4d92-9ba4-e5ae5dce02fd
uuid: 3fb05cc7-f27a-4a79-8e98-544e4aabaf15
conditions:
id: rules_and
uuid: faf52a5f-beba-4b09-ac0a-f19f0d23cc52
uuid: 585b55af-847d-447a-afee-01b855807c4a
conditions: { }
actions:
id: rules_action_set
uuid: 7e0df904-755c-4c89-899b-9bb6212d5c6e
uuid: bb96d589-0d63-4b1b-89d7-faf358171d40
actions:
-
id: rules_action
uuid: bd3da549-41b5-4d92-9dbd-6dee9d35fadd
uuid: 60a1f348-f85f-45fc-a785-b279b522863a
context_values: { }
context_mapping:
entity: media
@ -39,7 +37,7 @@ expression:
action_id: islandora_update_event_generator
-
id: rules_action
uuid: 6aa1f15c-3a39-4af5-b577-81fa7081de62
uuid: ee50c8ae-a9cd-479a-aa86-3567629a01b8
context_values:
recipients:
- "activemq:queue:islandora-indexing-triplestore\r"

169
config/install/views.view.fedora_entities_reference.yml

@ -1,169 +0,0 @@
uuid: ec053572-be63-4209-a49a-16c09c9a3e73
langcode: en
status: true
dependencies:
module:
- islandora
- user
enforced:
module:
- islandora
_core:
default_config_hash: UU-ZHb4xUJIu4JMAIGXvy0c93Y_xq4CPibq1qrgp098
id: fedora_entities_reference
label: 'Fedora Entities Reference'
module: views
description: ''
tag: ''
base_table: fedora_resource_field_data
base_field: id
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: perm
options:
perm: 'access content'
cache:
type: tag
options: { }
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
query_tags: { }
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: mini
options:
items_per_page: 10
offset: 0
id: 0
total_pages: null
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
tags:
previous: ‹‹
next: ››
style:
type: default
row:
type: fields
fields:
name:
id: name
table: fedora_resource_field_data
field: name
entity_type: fedora_resource
entity_field: name
label: ''
alter:
alter_text: false
make_link: false
absolute: false
trim: false
word_boundary: false
ellipsis: false
strip_tags: false
html: false
hide_empty: false
empty_zero: false
settings:
link_to_entity: true
plugin_id: field
relationship: none
group_type: group
admin_label: ''
exclude: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_alter_empty: true
click_sort_column: value
type: string
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
filters:
status:
value: '1'
table: fedora_resource_field_data
field: status
plugin_id: boolean
entity_type: fedora_resource
entity_field: status
id: status
expose:
operator: ''
group: 1
sorts: { }
title: 'Bundles of Fedora'
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
- user.permissions
tags: { }
entity_reference_1:
display_plugin: entity_reference
id: entity_reference_1
display_title: 'All Fedora Resource Entities'
position: 2
display_options:
display_extenders: { }
style:
type: entity_reference
options:
search_fields:
name: name
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- user.permissions
tags: { }

216
config/install/views.view.membership_view.yml

@ -1,216 +0,0 @@
uuid: 84f7671f-475f-4b91-98d5-42182389414c
langcode: en
status: true
dependencies:
config:
- core.entity_view_mode.fedora_resource.teaser
enforced:
module:
- islandora
module:
- islandora
- user
_core:
default_config_hash: he4YnarZrhrqUnqtFXImn2pESaJQdTTWmFPyapSRwoM
id: membership_view
label: 'Membership View'
module: views
description: 'Displays a list of member resources'
tag: ''
base_table: fedora_resource_field_data
base_field: id
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: perm
options:
perm: 'view published fedora resource entities'
cache:
type: tag
options: { }
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
query_tags: { }
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: mini
options:
items_per_page: 10
offset: 0
id: 0
total_pages: null
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
tags:
previous: ‹‹
next: ››
style:
type: default
options:
row_class: ''
default_row_class: true
uses_fields: false
row:
type: 'entity:fedora_resource'
options:
relationship: none
view_mode: teaser
fields:
name:
id: name
table: fedora_resource_field_data
field: name
entity_type: fedora_resource
entity_field: name
label: ''
alter:
alter_text: false
make_link: false
absolute: false
trim: false
word_boundary: false
ellipsis: false
strip_tags: false
html: false
hide_empty: false
empty_zero: false
settings:
link_to_entity: true
plugin_id: field
relationship: none
group_type: group
admin_label: ''
exclude: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_alter_empty: true
click_sort_column: value
type: string
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
filters: { }
sorts: { }
header: { }
footer: { }
empty: { }
relationships: { }
arguments:
field_memberof_target_id:
id: field_memberof_target_id
table: fedora_resource__field_memberof
field: field_memberof_target_id
relationship: none
group_type: group
admin_label: ''
default_action: empty
exception:
value: all
title_enable: false
title: All
title_enable: false
title: ''
default_argument_type: fixed
default_argument_options:
argument: ''
default_argument_skip_url: false
summary_options:
base_path: ''
count: true
items_per_page: 25
override: false
summary:
sort_order: asc
number_of_records: 0
format: default_summary
specify_validation: false
validate:
type: none
fail: 'not found'
validate_options: { }
break_phrase: false
not: false
plugin_id: numeric
display_extenders: { }
title: Members
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
- user.permissions
tags: { }
page:
display_plugin: page
id: page
display_title: Members
position: 2
display_options:
display_extenders: { }
path: fedora_resource/%fedora_resource/members
menu:
type: tab
title: Members
description: 'A list of members of this resource'
expanded: false
parent: ''
weight: -1
context: '0'
menu_name: main
tab_options:
type: none
title: ''
description: ''
weight: 0
display_description: 'Members of {{ name }}'
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
- user.permissions
tags: { }

24
config/schema/fedora_resource_type.schema.yml

@ -1,24 +0,0 @@
islandora.fedora_resource_type.*:
type: config_entity
label: 'Fedora resource type config'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
uuid:
type: string
# Plugin \Drupal\islandora\Plugin\Search\FedoraResourceSearch
search.plugin.node_search:
type: mapping
label: 'Fedora Resource search'
mapping:
rankings:
type: sequence
label: 'Content ranking'
sequence:
type: integer
label: 'Influence'

71
fedora_resource.page.inc

@ -1,71 +0,0 @@
<?php
/**
* @file
* Contains fedora_resource.page.inc.
*
* Page callback for Fedora resource entities.
*
* This file is part of the Islandora Project.
*
* (c) Islandora Foundation
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Diego Pino Navarro <dpino@metro.org> https://github.com/diegopino
*/
use Drupal\Core\Render\Element;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Prepares variables for Fedora resource templates.
*
* Default template: fedora_resource.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the user information and any
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_fedora_resource(array &$variables) {
// Fetch FedoraResource Entity Object.
$fedora_resource = $variables['elements']['#fedora_resource'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
/**
* Prepares variables for a custom entity type creation list templates.
*
* Default template: fedora_resource-content-add-list.html.twig.
*
* @param array $variables
* An associative array containing:
* - content: An array of fedora_resource-types.
*
* @see block_content_add_page()
*/
function template_preprocess_fedora_resource_content_add_list(array &$variables) {
$variables['types'] = [];
$query = \Drupal::request()->query->all();
foreach ($variables['content'] as $type) {
$variables['types'][$type->id()] = [
'link' => Link::fromTextAndUrl($type->label(), new Url('entity.fedora_resource.add_form', [
'fedora_resource_type' => $type->id(),
], ['query' => $query])),
'description' => [
'#markup' => $type->label(),
],
'title' => $type->label(),
'localized_options' => [
'query' => $query,
],
];
}
}

18
islandora.install

@ -5,6 +5,8 @@
* Install/update hook implementations.
*/
use Drupal\rest\Entity\RestResourceConfig;
/**
* Implements hook_schema().
*/
@ -40,3 +42,19 @@ function islandora_schema() {
];
return $schema;
}
/**
* Implemets hook_install().
*/
function islandora_install() {
$rest_config = RestResourceConfig::load('entity.node');
$configuration = [
'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
'formats' => ['hal_json', 'jsonld'],
'authentication' => ['basic_auth', 'jwt_auth', 'cookie'],
];
$rest_config->set('configuration', $configuration);
$rest_config->save(TRUE);
}

10
islandora.links.action.yml

@ -1,10 +0,0 @@
entity.fedora_resource.add_form:
route_name: 'fedora_resource.add_page'
title: 'Add Fedora resource'
appears_on:
- entity.fedora_resource.collection
entity.fedora_resource_type.add_form:
route_name: 'entity.fedora_resource_type.add_form'
title: 'Add Fedora resource type'
appears_on:
- entity.fedora_resource_type.collection

8
islandora.links.menu.yml

@ -1,11 +1,3 @@
# Fedora resource type menu items definition
entity.fedora_resource_type.collection:
title: 'Fedora resource type list'
route_name: entity.fedora_resource_type.collection
description: 'List Fedora resource type (bundles)'
parent: system.admin_structure
weight: 99
# Menu list of Islandora configuration forms
system.admin_config_islandora:
title: Islandora

21
islandora.links.task.yml

@ -1,21 +0,0 @@
# Fedora resource routing definition
entity.fedora_resource.canonical:
route_name: entity.fedora_resource.canonical
base_route: entity.fedora_resource.canonical
title: 'View'
entity.fedora_resource.edit_form:
route_name: entity.fedora_resource.edit_form
base_route: entity.fedora_resource.canonical
title: Edit
entity.fedora_resource.delete_form:
route_name: entity.fedora_resource.delete_form
base_route: entity.fedora_resource.canonical
title: Delete
weight: 10
entity.fedora_resource.collection:
route_name: entity.fedora_resource.collection
base_route: system.admin_content
title: 'Fedora Resources'

40
islandora.module

@ -34,40 +34,6 @@ function islandora_help($route_name, RouteMatchInterface $route_match) {
}
}
/**
* Implements hook_theme().
*/
function islandora_theme() {
$theme = [];
$theme['fedora_resource'] = [
'render element' => 'elements',
'file' => 'fedora_resource.page.inc',
'template' => 'fedora_resource',
];
$theme['fedora_resource_content_add_list'] = [
'render element' => 'content',
'variables' => ['content' => NULL],
'file' => 'fedora_resource.page.inc',
];
return $theme;
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function islandora_theme_suggestions_fedora_resource(array $variables) {
$suggestions = [];
$entity = $variables['elements']['#fedora_resource'];
$sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
$suggestions[] = 'fedora_resource__' . $sanitized_view_mode;
$suggestions[] = 'fedora_resource__' . $entity->bundle();
$suggestions[] = 'fedora_resource__' . $entity->bundle() . '__' . $sanitized_view_mode;
$suggestions[] = 'fedora_resource__' . $entity->id();
$suggestions[] = 'fedora_resource__' . $entity->id() . '__' . $sanitized_view_mode;
return $suggestions;
}
/**
* Implements hook_rdf_namespaces().
*/
@ -92,7 +58,7 @@ function islandora_rdf_namespaces() {
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function islandora_fedora_resource_insert(EntityInterface $entity) {
function islandora_node_insert(EntityInterface $entity) {
// Creates a record in the db to track the number of changes to the entity.
$versionCounter = \Drupal::service('islandora.versioncounter');
try {
@ -110,7 +76,7 @@ function islandora_fedora_resource_insert(EntityInterface $entity) {
/**
* Implements hook_ENTITY_TYPE_update().
*/
function islandora_fedora_resource_update(EntityInterface $entity) {
function islandora_node_update(EntityInterface $entity) {
// Increments the number of changes to the entity.
$versionCounter = \Drupal::service('islandora.versioncounter');
$versionCounter->increment($entity->uuid());
@ -119,7 +85,7 @@ function islandora_fedora_resource_update(EntityInterface $entity) {
/**
* Implements hook_ENTITY_TYPE_update().
*/
function islandora_fedora_resource_delete(EntityInterface $entity) {
function islandora_node_delete(EntityInterface $entity) {
// Deletes the record in the db to track the number of changes to the entity.
$versionCounter = \Drupal::service('islandora.versioncounter');
$versionCounter->delete($entity->uuid());

26
islandora.permissions.yml

@ -1,26 +0,0 @@
# Fedora Resource permissions
add fedora resource entities:
title: 'Create new Fedora resource entities'
administer fedora resource entities:
title: 'Administer Fedora resource entities'
description: 'Allow to access the administration form to configure Fedora resource entities.'
restrict access: true
delete fedora resource entities:
title: 'Delete Fedora resource entities'
edit fedora resource entities:
title: 'Edit Fedora resource entities'
view published fedora resource entities:
title: 'View published Fedora resource entities'
view unpublished fedora resource entities:
title: 'View unpublished Fedora resource entities'
# Fedora Resource Type permissions
administer fedora resource type entities:
title: 'Administer Fedora Resource Type entities'
description: 'Allow to access administration of Fedora Resource Type entities (bundles).'
restrict access: true

10
islandora.routing.yml

@ -17,13 +17,9 @@ system.islandora_settings:
_permission: 'administer site configuration'
# Islandora JSON-LD Routing definition
entity.fedora_resource_type.jsonldcontext:
path: '/fedora_resource_context/{bundle}'
islandora.jsonldcontext:
path: '/context/{entity_type}/{bundle}'
defaults:
_controller: '\Drupal\islandora\Controller\FedoraResourceJsonLdContextController::content'
_controller: '\Drupal\islandora\Controller\JsonLdContextController::content'
requirements:
_permission: 'access content'
options:
parameters:
bundle:
type: entity:{fedora_resource}:{fedora_resource_type}

119
src/Controller/FedoraResourceAddController.php

@ -1,119 +0,0 @@
<?php
namespace Drupal\islandora\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Class FedoraResourceAddController.
*
* @package Drupal\islandora\Controller
*/
class FedoraResourceAddController extends ControllerBase {
/**
* The Entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $storage;
/**
* The Entity storage type.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $typeStorage;
/**
* FedoraResourceAddController constructor.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The Entity storage.
* @param \Drupal\Core\Entity\EntityStorageInterface $type_storage
* The Entity storage type.
*/
public function __construct(EntityStorageInterface $storage, EntityStorageInterface $type_storage) {
$this->storage = $storage;
$this->typeStorage = $type_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
/** @var EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager = $container->get('entity_type.manager');
return new static(
$entity_type_manager->getStorage('fedora_resource'),
$entity_type_manager->getStorage('fedora_resource_type')
);
}
/**
* Displays add links for available bundles/types for entity fedora_resource.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return array
* A render array for a list of the fedora_resource bundles/types that can
* be added or if there is only one type/bunlde defined for the site, the
* function returns the add page for that bundle/type.
*/
public function add(Request $request) {
$types = $this->typeStorage->loadMultiple();
if ($types && count($types) == 1) {
$type = reset($types);
return $this->addForm($type, $request);
}
if (count($types) === 0) {
return [
'#markup' => $this->t('You have not created any %bundle types yet. @link to add a new type.', [
'%bundle' => 'Fedora resource',
'@link' => $this->l($this->t('Go to the type creation page'), Url::fromRoute('entity.fedora_resource_type.add_form')),
]),
];
}
return ['#theme' => 'fedora_resource_content_add_list', '#content' => $types];
}
/**
* Presents the creation form for fedora_resource entities of given type.
*
* @param \Drupal\Core\Entity\EntityInterface $fedora_resource_type
* The custom bundle to add.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return array
* A form array as expected by drupal_render().
*/
public function addForm(EntityInterface $fedora_resource_type, Request $request) {
$entity = $this->storage->create([
'type' => $fedora_resource_type->id(),
]);
return $this->entityFormBuilder()->getForm($entity);
}
/**
* Provides the page title for this controller.
*
* @param \Drupal\Core\Entity\EntityInterface $fedora_resource_type
* The custom bundle/type being added.
*
* @return string
* The page title.
*/
public function getAddFormTitle(EntityInterface $fedora_resource_type) {
return t('Create of bundle @label',
['@label' => $fedora_resource_type->label()]
);
}
}

16
src/Controller/FedoraResourceJsonLdContextController.php → src/Controller/JsonLdContextController.php

@ -13,11 +13,11 @@ use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
/**
* Class FedoraResourceJsonLdContextController.
* Class JsonLdContextController.
*
* @package Drupal\islandora\Controller
*/
class FedoraResourceJsonLdContextController extends ControllerBase {
class JsonLdContextController extends ControllerBase {
/**
* Injected JsonldContextGenerator.
@ -27,7 +27,7 @@ class FedoraResourceJsonLdContextController extends ControllerBase {
private $jsonldContextGenerator;
/**
* FedoraResourceJsonLdContextController constructor.
* JsonLdContextController constructor.
*
* @param \Drupal\jsonld\ContextGenerator\JsonldContextGeneratorInterface $jsonld_context_generator
* Injected JsonldContextGenerator.
@ -50,8 +50,10 @@ class FedoraResourceJsonLdContextController extends ControllerBase {
}
/**
* Returns an JSON-LD Context for a fedora_resource bundle.
* Returns an JSON-LD Context for a entity bundle.
*
* @param string $entity_type
* Route argument, an entity type.
* @param string $bundle
* Route argument, a bundle.
* @param \Symfony\Component\HttpFoundation\Request $request
@ -60,12 +62,12 @@ class FedoraResourceJsonLdContextController extends ControllerBase {
* @return \Symfony\Component\HttpFoundation\Response
* An Http response.
*/
public function content($bundle, Request $request) {
public function content($entity_type, $bundle, Request $request) {
// TODO: expose cached/not cached through
// more varied HTTP response codes.
try {
$context = $this->jsonldContextGenerator->getContext('fedora_resource.' . $bundle);
$context = $this->jsonldContextGenerator->getContext("$entity_type.$bundle");
$response = new CacheableJsonResponse(json_decode($context), 200);
$response->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
$response->headers->set('X-Powered-By', 'Islandora CLAW API');
@ -74,7 +76,7 @@ class FedoraResourceJsonLdContextController extends ControllerBase {
// For now deal with Cache dependencies manually.
$meta = new CacheableMetadata();
$meta->setCacheContexts(['user.permissions', 'ip', 'url']);
$meta->setCacheTags(RdfMapping::load('fedora_resource.' . $bundle)->getCacheTags());
$meta->setCacheTags(RdfMapping::load("$entity_type.$bundle")->getCacheTags());
$meta->setCacheMaxAge(Cache::PERMANENT);
$response->addCacheableDependency($meta);
}

465
src/Entity/FedoraResource.php

@ -1,465 +0,0 @@
<?php
namespace Drupal\islandora\Entity;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\islandora\FedoraResourceInterface;
use Drupal\user\UserInterface;
/**
* Defines the Fedora resource entity.
*
* @ingroup islandora
*
* @ContentEntityType(
* id = "fedora_resource",
* label = @Translation("Fedora resource"),
* bundle_label = @Translation("Fedora resource type"),
* handlers = {
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "list_builder" = "Drupal\islandora\FedoraResourceListBuilder",
* "views_data" = "Drupal\islandora\Entity\FedoraResourceViewsData",
* "inline_form" = "Drupal\islandora\Form\FedoraResourceEntityInlineForm",
* "form" = {
* "default" = "Drupal\islandora\Form\FedoraResourceForm",
* "add" = "Drupal\islandora\Form\FedoraResourceForm",
* "edit" = "Drupal\islandora\Form\FedoraResourceForm",
* "delete" = "Drupal\islandora\Form\FedoraResourceDeleteForm",
* },
* "access" = "Drupal\islandora\FedoraResourceAccessControlHandler",
* "route_provider" = {
* "html" = "Drupal\islandora\FedoraResourceHtmlRouteProvider",
* },
* },
* base_table = "fedora_resource",
* data_table = "fedora_resource_field_data",
* revision_table = "fedora_resource_revision",
* revision_data_table = "fedora_resource_field_data_revision",
* translatable = TRUE,
* admin_permission = "administer fedora resource entities",
* entity_keys = {
* "id" = "id",
* "revision" = "vid",
* "bundle" = "type",
* "label" = "name",
* "uuid" = "uuid",
* "uid" = "user_id",
* "langcode" = "langcode",
* "status" = "status",
* },
* common_reference_target = TRUE,
* permission_granularity = "bundle",
* links = {
* "canonical" = "/fedora_resource/{fedora_resource}",
* "uuid" = "/islandora_uuid/{fedora_resource}",
* "add-form" = "/fedora_resource/add/{fedora_resource_type}",
* "edit-form" = "/fedora_resource/{fedora_resource}/edit",
* "delete-form" = "/fedora_resource/{fedora_resource}/delete",
* "collection" = "/admin/content/fedora_resource",
* },
* bundle_entity_type = "fedora_resource_type",
* field_ui_base_route = "entity.fedora_resource_type.edit_form"
* )
*/
class FedoraResource extends ContentEntityBase implements FedoraResourceInterface {
use EntityChangedTrait;
/**
* Gets an array of placeholders for Fedora Resource Entity.
*
* We are overriding this method to add additional uuid
* placeholders.
*
* @param string $rel
* The link relationship type, for example: canonical or edit-form.
*
* @return array
* An array of URI placeholders.
*/
protected function urlRouteParameters($rel) {
// TODO: Change the autogenerated stub.
$uri_route_parameters = parent::urlRouteParameters($rel);
if ($rel === 'uuid') {
$uri_route_parameters[$this->getEntityTypeId()] = $this->uuid();
}
return $uri_route_parameters;
}
/**
* {@inheritdoc}
*/
public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
parent::preCreate($storage_controller, $values);
$values += [
'user_id' => \Drupal::currentUser()->id(),
];
}
/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
// Reindex the entity when it is updated. The entity is automatically
// indexed when it is added, simply by being added to the {fedora_resource}
// table. Only required if using the core search index.
if ($update) {
if (\Drupal::moduleHandler()->moduleExists('search')) {
search_mark_for_reindex('fedora_resource_search', $this->id());
}
}
}
/**
* {@inheritdoc}
*/
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
// This removes references to deleted parents. But this could be
// used to remove child entities instead.
foreach ($entities as $entity) {
if ($entity->getEntityType()->getBundleEntityType() == 'fedora_resource_type') {
$references = self::getInboundReferences($entity);
if ($references) {
$ref_entities = $storage->loadMultiple($references);
foreach ($ref_entities as $ref_entity) {
$ref_entity->removeParent();
$ref_entity->save();
}
}
}
}
}
/**
* {@inheritdoc}
*/
public function getType() {
return $this->bundle();
}
/**
* {@inheritdoc}
*/
public function getName() {
return $this->get('name')->value;
}
/**
* {@inheritdoc}
*/
public function setName($name) {
$this->set('name', $name);
return $this;
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function setCreatedTime($timestamp) {
$this->set('created', $timestamp);
return $this;
}
/**
* {@inheritdoc}
*/
public function getOwner() {
return $this->get('user_id')->entity;
}
/**
* {@inheritdoc}
*/
public function getOwnerId() {
return $this->get('user_id')->target_id;
}
/**
* {@inheritdoc}
*/
public function setOwnerId($uid) {
$this->set('user_id', $uid);
return $this;
}
/**
* {@inheritdoc}
*/
public function setOwner(UserInterface $account) {
$this->set('user_id', $account->id());
return $this;
}
/**
* {@inheritdoc}
*/
public function isPublished() {
return (bool) $this->getEntityKey('status');
}
/**
* {@inheritdoc}
*/
public function setPublished($published) {
$this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
return $this;
}
/**
* {@inheritdoc}
*/
public function hasParent() {
return (!$this->get('fedora_has_parent')->isEmpty());
}
/**
* {@inheritdoc}
*/
public function getParent() {
return $this->get('fedora_has_parent')
->first()
->get('entity')
->getTarget()
->getValue();
}
/**
* {@inheritdoc}
*/
public function getParentId() {
return $this->get('fedora_has_parent')
->first()
->get('entity')
->getTarget()
->getValue()
->id();
}
/**
* {@inheritdoc}
*/
public function setParent(FedoraResourceInterface $entity) {
$this->set('fedora_has_parent', $entity);
return $this;
}
/**
* {@inheritdoc}
*/
public function removeParent() {
$this->set('fedora_has_parent', NULL);
return $this;
}
/**
* Default value callback for 'fedora_has_parent' base field definition.
*
* @see ::baseFieldDefinitions()
*
* @return array
* An array of default values.
*/
public static function getFedoraRoot() {
// Just stub code, we need to figure out what "root is" in this context.
return NULL;
}
/**
* Get all the objects that have $entity as a fedora_has_parent.
*
* @param \Drupal\islandora\FedoraResourceInterface $entity
* The entity to find inbound references for.
*
* @return array
* An array of entity ids
*/
protected static function getInboundReferences(FedoraResourceInterface $entity) {
// TODO: Not use static loading.
$query = \Drupal::entityQuery('fedora_resource');
$query->condition('fedora_has_parent', $entity->id());
return $query->execute();
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields['id'] = BaseFieldDefinition::create('integer')
->setLabel(t('ID'))
->setDescription(t('The ID of the Fedora resource entity.'))
->setReadOnly(TRUE);
$fields['vid'] = BaseFieldDefinition::create('integer')
->setLabel(t('Revision ID'))
->setDescription(t('The Fedora resource revision ID.'))
->setReadOnly(TRUE)
->setSetting('unsigned', TRUE);
$fields['type'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Type'))
->setDescription(t('The Fedora resource type/bundle.'))
->setSetting('target_type', 'fedora_resource_type')
->setRequired(TRUE);
$fields['uuid'] = BaseFieldDefinition::create('uuid')
->setLabel(t('UUID'))
->setDescription(t('The UUID of the Fedora resource entity.'))
->setReadOnly(TRUE);
$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setDescription(t('The user ID of author of the Fedora resource entity.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
->setTranslatable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'author',
'weight' => 0,
])
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => 5,
'settings' => [
'match_operator' => 'CONTAINS',
'size' => '60',
'autocomplete_type' => 'tags',
'placeholder' => '',
],
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
// Removing from form and display until we get behaviour sorted out.
$fields['fedora_has_parent'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Fedora has Parent'))
->setDescription(t('Parent Fedora Resource.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'fedora_resource')
->setSetting('handler', 'default')
->setDefaultValueCallback('\Drupal\islandora\Entity\FedoraResource::getFedoraRoot')
->setTranslatable(TRUE)
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('view', FALSE);
$fields['name'] = BaseFieldDefinition::create('string')
->setLabel(t('Name'))
->setDescription(t('The name of the Fedora resource entity.'))
->setSettings([
'max_length' => 50,
'text_processing' => 0,
])
->setDefaultValue('')
->setDisplayOptions('view', [
'label' => 'above',
'type' => 'string',
'weight' => -4,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -4,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['status'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Publishing status'))
->setDescription(t('A boolean indicating whether the Fedora resource is published.'))
->setDefaultValue(TRUE);
$fields['langcode'] = BaseFieldDefinition::create('language')
->setLabel(t('Language code'))
->setDescription(t('The language code for the Fedora resource entity.'))
->setDisplayOptions('form', [
'type' => 'language_select',
'weight' => 10,
])
->setDisplayConfigurable('form', TRUE);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Created'))
->setDescription(t('The time that the entity was created.'));
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time that the entity was last edited.'));
$fields['promote'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Promoted to front page'))
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDefaultValue(TRUE)
->setDisplayOptions('form', [
'type' => 'boolean_checkbox',
'settings' => [
'display_label' => TRUE,
],
'weight' => 15,
])
->setDisplayConfigurable('form', TRUE);
$fields['sticky'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Sticky at top of lists'))
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDefaultValue(FALSE)
->setDisplayOptions('form', [
'type' => 'boolean_checkbox',
'settings' => [
'display_label' => TRUE,
],
'weight' => 16,
])
->setDisplayConfigurable('form', TRUE);
$fields['revision_timestamp'] = BaseFieldDefinition::create('created')
->setLabel(t('Revision timestamp'))
->setDescription(t('The time that the current revision was created.'))
->setQueryable(FALSE)
->setRevisionable(TRUE);
$fields['revision_uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Revision user ID'))
->setDescription(t('The user ID of the author of the current revision.'))
->setSetting('target_type', 'user')
->setQueryable(FALSE)
->setRevisionable(TRUE);
$fields['revision_log'] = BaseFieldDefinition::create('string_long')
->setLabel(t('Revision log message'))
->setDescription(t('Briefly describe the changes you have made.'))
->setRevisionable(TRUE)
->setDefaultValue('')
->setDisplayOptions('form', [
'type' => 'string_textarea',
'weight' => 25,
'settings' => [
'rows' => 4,
],
]);
$fields['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Revision translation affected'))
->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
->setReadOnly(TRUE)
->setRevisionable(TRUE)
->setTranslatable(TRUE);
return $fields;
}
}

57
src/Entity/FedoraResourceType.php

@ -1,57 +0,0 @@
<?php
namespace Drupal\islandora\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\islandora\FedoraResourceTypeInterface;
/**
* Defines the Fedora resource type entity.
*
* @ConfigEntityType(
* id = "fedora_resource_type",
* label = @Translation("Fedora resource type"),
* handlers = {
* "list_builder" = "Drupal\islandora\FedoraResourceTypeListBuilder",
* "form" = {
* "add" = "Drupal\islandora\Form\FedoraResourceTypeForm",
* "edit" = "Drupal\islandora\Form\FedoraResourceTypeForm",
* "delete" = "Drupal\islandora\Form\FedoraResourceTypeDeleteForm"
* },
* "route_provider" = {
* "html" = "Drupal\islandora\FedoraResourceTypeHtmlRouteProvider",
* },
* },
* config_prefix = "fedora_resource_type",
* admin_permission = "administer site configuration",
* bundle_of = "fedora_resource",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* "uuid" = "uuid"
* },
* links = {
* "add-form" = "/admin/structure/fedora_resource_type/add",
* "edit-form" = "/admin/structure/fedora_resource_type/{fedora_resource_type}/edit",
* "delete-form" = "/admin/structure/fedora_resource_type/{fedora_resource_type}/delete",
* "collection" = "/admin/structure/fedora_resource_type"
* }
* )
*/
class FedoraResourceType extends ConfigEntityBundleBase implements FedoraResourceTypeInterface {
/**
* The Fedora resource type ID.
*
* @var string
*/
protected $id;
/**
* The Fedora resource type label.
*
* @var string
*/
protected $label;
}

31
src/Entity/FedoraResourceViewsData.php

@ -1,31 +0,0 @@
<?php
namespace Drupal\islandora\Entity;
use Drupal\views\EntityViewsData;
use Drupal\views\EntityViewsDataInterface;
/**
* Provides Views data for Fedora resource entities.
*/
class FedoraResourceViewsData extends EntityViewsData implements EntityViewsDataInterface {
/**
* {@inheritdoc}
*/
public function getViewsData() {
$data = parent::getViewsData();
$data['fedora_resource']['table']['base'] = [
'field' => 'id',
'title' => $this->t('Fedora resource'),
'help' => $this->t('The Fedora resource ID.'),
];
$data['fedora_resource_field_data']['table']['wizard_id'] = 'fedora_resource';
$data['fedora_resource_field_revision']['table']['wizard_id'] = 'fedora_resource_revision';
return $data;
}
}

48
src/FedoraResourceAccessControlHandler.php

@ -1,48 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
/**
* Access controller for the Fedora resource entity.
*
* @see \Drupal\islandora\Entity\FedoraResource.
* @ingroup islandora
*/
class FedoraResourceAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\islandora\FedoraResourceInterface $entity */
switch ($operation) {
case 'view':
if (!$entity->isPublished()) {
return AccessResult::allowedIfHasPermission($account, 'view unpublished fedora resource entities');
}
return AccessResult::allowedIfHasPermission($account, 'view published fedora resource entities');
case 'update':
return AccessResult::allowedIfHasPermission($account, 'edit fedora resource entities');
case 'delete':
return AccessResult::allowedIfHasPermission($account, 'delete fedora resource entities');
}
// Unknown operation, no opinion.
return AccessResult::neutral();
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessResult::allowedIfHasPermission($account, 'add fedora resource entities');
}
}

184
src/FedoraResourceHtmlRouteProvider.php

@ -1,184 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Component\Uuid\Uuid;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Drupal\Core\Entity\Routing\EntityRouteProviderInterface;
use Symfony\Component\Routing\Route;
/**
* Provides routes for Fedora resource entities.
*
* @see Drupal\Core\Entity\Routing\AdminHtmlRouteProvider
* @see Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
* @ingroup islandora
*/
class FedoraResourceHtmlRouteProvider extends AdminHtmlRouteProvider implements EntityRouteProviderInterface {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
$entity_type_id = $entity_type->id();
if ($collection_route = $this->getCollectionRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.collection", $collection_route);
}
if ($add_form_route = $this->getAddFormRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.add_form", $add_form_route);
}
$add_page_route = $this->getAddPageRoute($entity_type);
$collection->add("$entity_type_id.add_page", $add_page_route);
if ($settings_form_route = $this->getSettingsFormRoute($entity_type)) {
$collection->add("$entity_type_id.settings", $settings_form_route);
}
if ($uuid_route = $this->getUuidRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.uuid", $uuid_route);
}
return $collection;
}
/**
* Gets the UUID route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getUuidRoute(EntityTypeInterface $entity_type) {
if ($entity_type->getKey('uuid') && $entity_type->hasViewBuilderClass() && $entity_type->hasLinkTemplate('uuid')) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('uuid'));
$route
->addDefaults([
'_entity_view' => "{$entity_type_id}.full",
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
])
->setRequirement('_entity_access', "{$entity_type_id}.view")
->setOption('parameters', [
$entity_type_id => ['type' => "uuid"],
])
// Fetch UUID pattern from Uuid class(constant)
->setRequirement($entity_type_id, '^' . Uuid::VALID_PATTERN . '$');
return $route;
}
}
/**
* Gets the collection route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getCollectionRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('collection') && $entity_type->hasListBuilderClass()) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('collection'));
$route
->setDefaults([
'_entity_list' => $entity_type_id,
'_title' => "{$entity_type->getLabel()} list",
])
->setRequirement('_permission', 'view fedora resource entities')
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the add-form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getAddFormRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('add-form')) {
$entity_type_id = $entity_type->id();
$parameters = [
$entity_type_id => ['type' => 'entity:' . $entity_type_id],
];
$route = new Route($entity_type->getLinkTemplate('add-form'));
$bundle_entity_type_id = $entity_type->getBundleEntityType();
// Content entities with bundles are added via a dedicated controller.
$route
->setDefaults([
'_controller' => 'Drupal\islandora\Controller\FedoraResourceAddController::addForm',
'_title_callback' => 'Drupal\islandora\Controller\FedoraResourceAddController::getAddFormTitle',
])
->setRequirement('_entity_create_access', $entity_type_id . ':{' . $bundle_entity_type_id . '}');
$parameters[$bundle_entity_type_id] = ['type' => 'entity:' . $bundle_entity_type_id];
$route
->setOption('parameters', $parameters)
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the add page route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getAddPageRoute(EntityTypeInterface $entity_type) {
$route = new Route("/admin/structure/{$entity_type->id()}/add");
$route
->setDefaults([
'_controller' => 'Drupal\islandora\Controller\FedoraResourceAddController::add',
'_title' => "Add {$entity_type->getLabel()}",
])
->setRequirement('_entity_create_access', $entity_type->id())
->setOption('_admin_route', TRUE);
return $route;
}
/**
* Gets the settings form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getSettingsFormRoute(EntityTypeInterface $entity_type) {
if (!$entity_type->getBundleEntityType()) {
$route = new Route("/admin/structure/{$entity_type->id()}/settings");
$route
->setDefaults([
'_form' => 'Drupal\islandora\Form\FedoraResourceSettingsForm',
'_title' => "{$entity_type->getLabel()} settings",
])
->setRequirement('_permission', $entity_type->getAdminPermission())
->setOption('_admin_route', TRUE);
return $route;
}
}
}

119
src/FedoraResourceInterface.php

@ -1,119 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface for defining Fedora resource entities.
*
* @ingroup islandora
*/
interface FedoraResourceInterface extends ContentEntityInterface, EntityChangedInterface, EntityOwnerInterface {
/**
* Gets the Fedora resource type.
*
* @return string
* The Fedora resource type.
*/
public function getType();
/**
* Gets the Fedora resource name.
*
* @return string
* Name of the Fedora resource.
*/
public function getName();
/**
* Sets the Fedora resource name.
*
* @param string $name
* The Fedora resource name.
*
* @return \Drupal\islandora\FedoraResourceInterface
* The called Fedora resource entity.
*/
public function setName($name);
/**
* Gets the Fedora resource creation timestamp.
*
* @return int
* Creation timestamp of the Fedora resource.
*/
public function getCreatedTime();
/**
* Sets the Fedora resource creation timestamp.
*
* @param int $timestamp
* The Fedora resource creation timestamp.
*
* @return \Drupal\islandora\FedoraResourceInterface
* The called Fedora resource entity.
*/
public function setCreatedTime($timestamp);
/**
* Returns the Fedora resource published status indicator.
*
* Unpublished Fedora resource are only visible to restricted users.
*
* @return bool
* TRUE if the Fedora resource is published.
*/
public function isPublished();
/**
* Sets the published status of a Fedora resource.
*
* @param bool $published
* TRUE to set this Fedora resource to published, FALSE to set it to
* unpublished.
*
* @return \Drupal\islandora\FedoraResourceInterface
* The called Fedora resource entity.
*/
public function setPublished($published);
/**
* Does the entity have a parent entity?
*
* @return bool
* Whether a parent entity was set.
*/
public function hasParent();
/**
* Gets the id of the parent entity.
*
* @return int
* The id of the parent Fedora resource entity.
*/
public function getParentId();
/**
* Get the parent entity.
*
* @return \Drupal\islandora\FedoraResourceInterface
* The actual entity of the parent Fedora resource.
*/
public function getParent();
/**
* Get the parent entity.
*
* @param \Drupal\islandora\FedoraResourceInterface $entity
* The parent entity.
*
* @return \Drupal\islandora\FedoraResourceInterface
* The called Fedora resource entity.
*/
public function setParent(FedoraResourceInterface $entity);
}

48
src/FedoraResourceListBuilder.php

@ -1,48 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Link;
/**
* Defines a class to build a listing of Fedora resource entities.
*
* @ingroup islandora
*/
class FedoraResourceListBuilder extends EntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['id'] = $this->t('Fedora resource ID');
$header['name'] = $this->t('Name');
$header['parent'] = $this->t('Parent');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/* @var $entity \Drupal\islandora\Entity\FedoraResource */
$row['id'] = $entity->id();
$row['name'] = Link::fromTextAndUrl(
$entity->label(),
$entity->toUrl()
);
if ($entity->hasParent()) {
$row['parent'] = Link::fromTextAndUrl(
$entity->getParent()->label(),
$entity->getParent()->toUrl()
);
}
else {
$row['parent'] = $this->t("n/a");
}
return $row + parent::buildRow($entity);
}
}

97
src/FedoraResourceTypeHtmlRouteProvider.php

@ -1,97 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Symfony\Component\Routing\Route;
/**
* Provides routes for Fedora resource type entities.
*
* @see Drupal\Core\Entity\Routing\AdminHtmlRouteProvider
* @see Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
* @ingroup islandora
*/
class FedoraResourceTypeHtmlRouteProvider extends AdminHtmlRouteProvider {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
$entity_type_id = $entity_type->id();
if ($collection_route = $this->getCollectionRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.collection", $collection_route);
}
if ($add_form_route = $this->getAddFormRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.add_form", $add_form_route);
}
return $collection;
}
/**
* Gets the collection route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getCollectionRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('collection') && $entity_type->hasListBuilderClass()) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('collection'));
$route
->setDefaults([
'_entity_list' => $entity_type_id,
// Make sure this is not a TranslatableMarkup object as the
// TitleResolver translates this string again.
'_title' => (string) $entity_type->getLabel(),
])
->setRequirement('_permission', $entity_type->getAdminPermission())
->setOption('_admin_route', TRUE);
return $route;
}
}
/**
* Gets the add-form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getAddFormRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('add-form')) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('add-form'));
// Use the add form handler, if available, otherwise default.
$operation = 'default';
if ($entity_type->getFormClass('add')) {
$operation = 'add';
}
$route
->setDefaults([
'_entity_form' => "{$entity_type_id}.{$operation}",
'_title' => "Add {$entity_type->getLabel()}",
])
->setRequirement('_entity_create_access', $entity_type_id)
->setOption('parameters', [
$entity_type_id => ['type' => 'entity:' . $entity_type_id],
])
->setOption('_admin_route', TRUE);
return $route;
}
}
}

13
src/FedoraResourceTypeInterface.php

@ -1,13 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides an interface for defining Fedora resource type entities.
*/
interface FedoraResourceTypeInterface extends ConfigEntityInterface {
// Add get/set methods for your configuration properties here.
}

32
src/FedoraResourceTypeListBuilder.php

@ -1,32 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides a listing of Fedora resource type entities.
*/
class FedoraResourceTypeListBuilder extends ConfigEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Fedora resource type');
$header['id'] = $this->t('Machine name');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['id'] = $entity->id();
// You probably want a few more properties here...
return $row + parent::buildRow($entity);
}
}

18
src/FedoraResourceViewBuilder.php

@ -1,18 +0,0 @@
<?php
namespace Drupal\islandora;
use Drupal\node\NodeViewBuilder;
/**
* Class FedoraResourceViewBuilder view builder handler.
*
* @TODO this should manage how fedora_resource are build to be viewed.
*
* Right now we are just using Drupal\Core\Entity\EntityViewBuilder
* @ingroup islandora
*/
class FedoraResourceViewBuilder extends NodeViewBuilder {
}

15
src/Form/FedoraResourceDeleteForm.php

@ -1,15 +0,0 @@
<?php
namespace Drupal\islandora\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
/**
* Provides a form for deleting Fedora resource entities.
*
* @ingroup islandora
*/
class FedoraResourceDeleteForm extends ContentEntityDeleteForm {
}

287
src/Form/FedoraResourceEntityInlineForm.php

@ -1,287 +0,0 @@
<?php
namespace Drupal\islandora\Form;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\inline_entity_form\Form\EntityInlineForm;
use Drupal\inline_entity_form\InlineFormInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Generic entity inline form handler.
*/
class FedoraResourceEntityInlineForm extends EntityInlineForm implements InlineFormInterface {
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type managed by this handler.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* Module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Constructs the inline entity form controller.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*/
public function __construct(EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, EntityTypeInterface $entity_type) {
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->entityType = $entity_type;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$container->get('entity_field.manager'),
$container->get('entity_type.manager'),
$container->get('module_handler'),
$entity_type
);
}
/**
* {@inheritdoc}
*/
public function getEntityType() {
return $this->entityType;
}
/**
* {@inheritdoc}
*/
public function getEntityTypeLabels() {
$lowercase_label = $this->entityType->getLowercaseLabel();
return [
'singular' => $lowercase_label,
'plural' => t('@entity_type entities', ['@entity_type' => $lowercase_label]),
];
}
/**
* {@inheritdoc}
*/
public function getEntityLabel(EntityInterface $entity) {
return $entity->label();
}
/**
* {@inheritdoc}
*/
public function getTableFields($bundles) {
$definitions = $this->entityFieldManager->getBaseFieldDefinitions($this->entityType->id());
$label_key = $this->entityType->getKey('label');
$label_field_label = t('Label');
if ($label_key && isset($definitions[$label_key])) {
$label_field_label = $definitions[$label_key]->getLabel();
}
$bundle_key = $this->entityType->getKey('bundle');
$bundle_field_label = t('Type');
if ($bundle_key && isset($definitions[$bundle_key])) {
$bundle_field_label = $definitions[$bundle_key]->getLabel();
}
$fields = [];
$fields['label'] = [
'type' => 'label',
'label' => $label_field_label,
'weight' => 1,
];
if (count($bundles) > 1) {
$fields[$bundle_key] = [
'type' => 'field',
'label' => $bundle_field_label,
'weight' => 2,
'display_options' => [
'type' => 'entity_reference_label',
'settings' => ['link' => FALSE],
],
];
}
return $fields;
}
/**
* {@inheritdoc}
*/
public function entityForm(array $entity_form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_form['#entity'];
$form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
$form_display->buildForm($entity, $entity_form, $form_state);
$entity_form['#ief_element_submit'][] = [get_class($this), 'submitCleanFormState'];
// Allow other modules to alter the form.
$this->moduleHandler->alter('inline_entity_form_entity_form', $entity_form, $form_state);
return $entity_form;
}
/**
* {@inheritdoc}
*/
public function entityFormValidate(array &$entity_form, FormStateInterface $form_state) {
// Perform entity validation only if the inline form was submitted,
// skipping other requests such as file uploads.
$triggering_element = $form_state->getTriggeringElement();
if (!empty($triggering_element['#ief_submit_trigger'])) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_form['#entity'];
$this->buildEntity($entity_form, $entity, $form_state);
$form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
$form_display->validateFormValues($entity, $entity_form, $form_state);
$entity->setValidationRequired(FALSE);
foreach ($form_state->getErrors() as $name => $message) {
// $name may be unknown in $form_state and
// $form_state->setErrorByName($name, $message)
// may suppress the error message.
$form_state->setError($triggering_element, $message);
}
}
}
/**
* {@inheritdoc}
*/
public function entityFormSubmit(array &$entity_form, FormStateInterface $form_state) {
$form_state->cleanValues();
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_form['#entity'];
$this->buildEntity($entity_form, $entity, $form_state);
}
/**
* {@inheritdoc}
*/
public function save(EntityInterface $entity) {
$entity->save();
}
/**
* {@inheritdoc}
*/
public function delete($ids, $context) {
$storage_handler = $this->entityTypeManager->getStorage($this->entityType->id());
$entities = $storage_handler->loadMultiple($ids);
$storage_handler->delete($entities);
}
/**
* Builds an updated entity object based upon the submitted form values.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
protected function buildEntity(array $entity_form, ContentEntityInterface $entity, FormStateInterface $form_state) {
$form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
$form_display->extractFormValues($entity, $entity_form, $form_state);
// Invoke all specified builders for copying form values to entity fields.
if (isset($entity_form['#entity_builders'])) {
foreach ($entity_form['#entity_builders'] as $function) {
call_user_func_array($function, [
$entity->getEntityTypeId(),
$entity,
&$entity_form,
&$form_state,
]);
}
}
}
/**
* Cleans up the form state for a submitted entity form.
*
* After field_attach_submit() has run and the form has been closed, the form
* state still contains field data in $form_state->get('field'). Unless that
* data is removed, the next form with the same #parents (reopened add form,
* for example) will contain data (i.e. uploaded files) from the previous
* form.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*/
// @codingStandardsIgnoreLine
public static function submitCleanFormState(&$entity_form, FormStateInterface $form_state) {
$info = \Drupal::entityTypeManager()->getDefinition($entity_form['#entity_type']);
if (!$info->get('field_ui_base_route')) {
// The entity type is not fieldable, nothing to cleanup.
return;
}
$bundle = $entity_form['#entity']->bundle();
$instances = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_form['#entity_type'], $bundle);
foreach ($instances as $instance) {
$field_name = $instance->getName();
if (!empty($entity_form[$field_name]['#parents'])) {
$parents = $entity_form[$field_name]['#parents'];
array_pop($parents);
if (!empty($parents)) {
$field_state = [];
WidgetBase::setWidgetState($parents, $field_name, $form_state, $field_state);
}
}
}
}
/**
* Gets the form display for the given entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param string $form_mode
* The form mode.
*
* @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface
* The form display.
*/
protected function getFormDisplay(ContentEntityInterface $entity, $form_mode) {
return EntityFormDisplay::collectRenderDisplay($entity, $form_mode);
}
}

48
src/Form/FedoraResourceForm.php

@ -1,48 +0,0 @@
<?php
namespace Drupal\islandora\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for Fedora resource edit forms.
*
* @ingroup islandora
*/
class FedoraResourceForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
/* @var $entity \Drupal\islandora\Entity\FedoraResource */
$form = parent::buildForm($form, $form_state);
$entity = $this->entity;
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$entity = $this->entity;
$status = parent::save($form, $form_state);
switch ($status) {
case SAVED_NEW:
drupal_set_message($this->t('Created the %label Fedora resource.', [
'%label' => $entity->label(),
]));
break;
default:
drupal_set_message($this->t('Saved the %label Fedora resource.', [
'%label' => $entity->label(),
]));
}
$form_state->setRedirect('entity.fedora_resource.canonical', ['fedora_resource' => $entity->id()]);
}
}

55
src/Form/FedoraResourceSettingsForm.php

@ -1,55 +0,0 @@
<?php
namespace Drupal\islandora\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class FedoraResourceSettingsForm.
*
* @package Drupal\islandora\Form
*
* @ingroup islandora
*/
class FedoraResourceSettingsForm extends FormBase {
/**
* Returns a unique string identifying the form.
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'FedoraResource_settings';
}
/**
* Form submission handler.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Empty implementation of the abstract submit class.
}
/**
* Defines the settings form for Fedora resource entities.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array
* Form definition array.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['FedoraResource_settings']['#markup'] = 'Settings form for Fedora resource entities. Manage field settings here.';
return $form;
}
}

53
src/Form/FedoraResourceTypeDeleteForm.php

@ -1,53 +0,0 @@
<?php
namespace Drupal\islandora\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Builds the form to delete Fedora resource type entities.
*/
class FedoraResourceTypeDeleteForm extends EntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete %name?', ['%name' => $this->entity->label()]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('entity.fedora_resource_type.collection');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->entity->delete();
drupal_set_message(
$this->t('content @type: deleted @label.',
[
'@type' => $this->entity->bundle(),
'@label' => $this->entity->label(),
]
)
);
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

67
src/Form/FedoraResourceTypeForm.php

@ -1,67 +0,0 @@
<?php
namespace Drupal\islandora\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Class FedoraResourceTypeForm.
*
* @package Drupal\islandora\Form
*/
class FedoraResourceTypeForm extends EntityForm {
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$fedora_resource_type = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $fedora_resource_type->label(),
'#description' => $this->t("Label for the Fedora resource type."),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $fedora_resource_type->id(),
'#machine_name' => [
'exists' => '\Drupal\islandora\Entity\FedoraResourceType::load',
],
'#disabled' => !$fedora_resource_type->isNew(),
];
/* You will need additional form elements for your custom properties. */
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$fedora_resource_type = $this->entity;
$status = $fedora_resource_type->save();
switch ($status) {
case SAVED_NEW:
drupal_set_message($this->t('Created the %label Fedora resource type.', [
'%label' => $fedora_resource_type->label(),
]));
break;
default:
drupal_set_message($this->t('Saved the %label Fedora resource type.', [
'%label' => $fedora_resource_type->label(),
]));
}
$form_state->setRedirectUrl($fedora_resource_type->urlInfo('collection'));
}
}

839
src/Plugin/Search/FedoraEntitySearch.php

@ -1,839 +0,0 @@
<?php
namespace Drupal\islandora\Plugin\Search;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\Config;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\SelectExtender;
use Drupal\Core\Database\StatementInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessibleInterface;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Render\RendererInterface;
use Drupal\islandora\FedoraResourceInterface;
use Drupal\search\Plugin\ConfigurableSearchPluginBase;
use Drupal\search\Plugin\SearchIndexingInterface;
use Drupal\search\SearchQuery;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Handles searching for fedora_resource entities.
*
* Demonstrates integration with the search index using
* \Drupal\search\SearchQuery.
* \Drupal\search\SearchQuery adds some search
* features such as automatically including {search_dataset} in the
* query, weighting the the result scores based on the importance of individual
* words, etc.
* If these "extra features" aren't approprite for your custom content entity,
* see \Drupal\user\Plugin\Search\UserSearch as an example
* of not using \Drupal\search\SearchQuery.
*
* USAGE / INSTALLATION:
*
* # Place this plugin in the directory
* fedora_resource/Plugin/Search.
* # Clear caches (drush cr).
* # Add a "Content Entity Example Contacts" search page at
* /admin/config/search/pages and configure it as desired.
* # Confirm that the index status at dmin/config/search/pages
* accurately reflects the number of
* content_entity_example_contact items (the number of "contact"
* entities that you have created, which should be listed at
* /content_entity_example_contact/list
* # Run cron to add your entities to the search index.
*
* @see \Drupal\node\Plugin\Search\NodeSearch
* @see \Drupal\user\Plugin\Search\UserSearch
*
* Annotation for discovery by Search module.
* - 'id': unique machine name for this search plugin.
* Will be used for the `type` field in {search_index} and {search_dataset}.
* - 'title': Translatable title for the search page & navigation tab.
*
* @SearchPlugin(
* id = "fedora_resource_search",
* title = @Translation("fedora resource content search")
* )
*/
class FedoraResourceSearch extends ConfigurableSearchPluginBase implements AccessibleInterface, SearchIndexingInterface {
/**
* A database connection object.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* An entity manager object.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* A module manager object.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* A config object for 'search.settings'.
*
* @var \Drupal\Core\Config\Config
*/
protected $searchSettings;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The Drupal account to use for checking for access to advanced search.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* The Renderer service to format the username and entity.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* An array of additional rankings from hook_ranking().
*
* @var array
*/
protected $rankings;
/**
* The list of options and info for advanced search filters.
*
* Each entry in the array has the option as the key and for its value, an
* array that determines how the value is matched in the database query. The
* possible keys in that array are:
* - column: (required) Name of the database column to match against.
* - join: (optional) Information on a table to join. By default the data is
* matched against any tables joined in the $query declaration in
* findResults().
* - operator: (optional) OR or AND, defaults to OR.
*
* For advanced search to work, probably also must modify:
* - buildSearchUrlQuery() to build the redirect URL.
* - searchFormAlter() to add fields to advanced search form.
*
* Note: In our case joins aren't needed because the {contact} table is
* joined in findResults().
*
* @var array
*/
protected $advanced = [
'name' => [
'column' => 'c.name',
],
];
/**
* A constant for setting and checking the query string.
*/
const ADVANCED_FORM = 'advanced-form';
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('database'),
$container->get('entity.manager'),
$container->get('module_handler'),
$container->get('config.factory')->get('search.settings'),
$container->get('language_manager'),
$container->get('renderer'),
$container->get('current_user')
);
}
/**
* Constructs \Drupal\islandora\Plugin\Search\FedoraResourceSearch.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Database\Connection $database
* A database connection object.
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* An entity manager object.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* A module manager object.
* @param \Drupal\Core\Config\Config $search_settings
* A config object for 'search.settings'.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Render\RendererInterface $renderer
* Renderer.
* @param \Drupal\Core\Session\AccountInterface $account
* The $account object to use for checking for access to advanced search.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, Config $search_settings, LanguageManagerInterface $language_manager, RendererInterface $renderer, AccountInterface $account = NULL) {
$this->database = $database;
$this->entityManager = $entity_manager;
$this->moduleHandler = $module_handler;
$this->searchSettings = $search_settings;
$this->languageManager = $language_manager;
$this->renderer = $renderer;
$this->account = $account;
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->addCacheTags(['fedora_resource_list']);
}
/**
* {@inheritdoc}
*/
public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
$result = AccessResult::allowedIfHasPermission($account, 'access content');
return $return_as_object ? $result : $result->isAllowed();
}
/**
* {@inheritdoc}
*/
public function isSearchExecutable() {
// Contact search is executable if we have keywords or an advanced
// parameter.
// At least, we should parse out the parameters and see if there are any
// keyword matches in that case, rather than just printing out the
// "Please enter keywords" message.
return !empty($this->keywords) || (isset($this->searchParameters['f']) && count($this->searchParameters['f']));
}
/**
* {@inheritdoc}
*/
public function getType() {
return $this->getPluginId();
}
/**
* {@inheritdoc}
*/
public function execute() {
if ($this->isSearchExecutable()) {
$results = $this->findResults();
if ($results) {
return $this->prepareResults($results);
}
}
return [];
}
/**
* Queries to find search results, and sets status messages.
*
* This method can assume that $this->isSearchExecutable() has already been
* checked and returned TRUE.
*
* @return \Drupal\Core\Database\StatementInterface|null
* Results from search query execute() method, or NULL if the search
* failed.
*/
protected function findResults() {
$keys = $this->keywords;
// Build matching conditions.
$query = $this->database
->select('search_index', 'i', ['target' => 'replica'])
->extend('Drupal\search\SearchQuery')
->extend('Drupal\Core\Database\Query\PagerSelectExtender');
// Join on {contact} and {users_field_data} to get user's published status.
// This join on {contact} also serves the advanced search items
// (in $this->advanced) that are in {contact}.
$query->join('contact', 'c', 'c.id = i.sid');
$query->join('users_field_data', 'ufd', 'ufd.uid = c.user_id');
$query->condition('ufd.status', 1);
$query
->searchExpression($keys, $this->getPluginId());
// @todo ===============
// Handle advanced search filters in the f query string.
// \Drupal::request()->query->get('f') is an array that looks like this in
// the URL: ?f[]=first_name:Jane&f[]=gender:f
// So $parameters['f'] looks like:
// array('first_name:Jane', 'gender:f');
// We need to parse this out into query conditions, some of which go into
// the keywords string, and some of which are separate conditions.
//
// Note: advanced form fields are added in searchFormAlter(),
// and the URL containing the "f" parameter is built in
// buildSearchUrlQuery().
$parameters = $this->getParameters();
if (!empty($parameters['f']) && is_array($parameters['f'])) {
// @todo This loop should probably be moved to a helper function.
$filters = [];
// Match any query value that is an expected option and a value
// separated by ':' like 'first_name:Jane'.
$pattern = '/^(' . implode('|', array_keys($this->advanced)) . '):([^ ]*)/i';
foreach ($parameters['f'] as $item) {
if (preg_match($pattern, $item, $m)) {
// Use the matched value as the array key to eliminate duplicates.
$filters[$m[1]][$m[2]] = $m[2];
}
}
// Now turn these into query conditions. This assumes that everything in
// $filters is a known type of advanced search as defined in
// $this->advanced.
foreach ($filters as $option => $matched) {
$info = $this->advanced[$option];
// Insert additional conditions. By default, all use the OR operator.
$operator = empty($info['operator']) ? 'OR' : $info['operator'];
$where = new Condition($operator);
foreach ($matched as $value) {
$where->condition($info['column'], $value);
}
$query->condition($where);
if (!empty($info['join'])) {
$query->join($info['join']['table'], $info['join']['alias'], $info['join']['condition']);
}
}
}
// ===============
// Add the ranking expressions.
$this->addFedoraResourceRankings($query);
// Run the query.
$find = $query
// Add the language code of the indexed item to the result of the query,
// since the entity will be rendered using the respective language.
->fields('i', ['langcode'])
// And since SearchQuery makes these into GROUP BY queries, if we add
// a field, for PostgreSQL we also need to make it an aggregate or a
// GROUP BY. In this case, we want GROUP BY.
->groupBy('i.langcode')
->limit(10)
->execute();
// Check query status and set messages if needed.
$status = $query->getStatus();
if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
drupal_set_message($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]), 'warning');
}
if ($status & SearchQuery::LOWER_CASE_OR) {
drupal_set_message($this->t('Search for either of the two terms with uppercase OR. For example, cats OR dogs.'), 'warning');
}
if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
drupal_set_message($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'), 'warning');
}
return $find;
}
/**
* Prepares search results for rendering.
*
* @param \Drupal\Core\Database\StatementInterface $found
* Results found from a successful search query execute() method.
*
* @return array
* Array of search result item render arrays (empty array if no results).
*/
protected function prepareResults(StatementInterface $found) {
$results = [];
// 'fedora_resource' comes from the entity type id declared
// in the annotation for \Drupal\islandora\Entity\FedoraResource.
// Replace this with your entity's type id.
$entity_storage = $this->entityManager->getStorage('fedora_resource');
$entity_render = $this->entityManager->getViewBuilder('fedora_resource');
$keys = $this->keywords;
foreach ($found as $item) {
// Render the contact.
/** @var \Drupal\content_entity_example\ContactInterface $entity */
$entity = $entity_storage->load($item->sid)->getTranslation($item->langcode);
$build = $entity_render->view($entity, 'search_result', $item->langcode);
unset($build['#theme']);
// Uncomment to use removeFromSnippet() for excluding data from snippet.
/* $build['#pre_render'][] = array($this, 'removeFromSnippet'); */
// Build the snippet.
$rendered = $this->renderer->renderPlain($build);
$this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
// Allow other modules to add to snippet.
$rendered .= ' ' . $this->moduleHandler->invokeAll('fedora_resource_update_index', [$entity]);
$extra = $this->moduleHandler->invokeAll('fedora_resource_search_result', [$entity]);
$language = $this->languageManager->getLanguage($item->langcode);
$result = [
'link' => $entity->url(
'canonical',
[
'absolute' => TRUE,
'language' => $language,
]
),
'type' => 'Fedora Resource',
'title' => $entity->label(),
'contact' => $entity,
'extra' => $extra,
'score' => $item->calculated_score,
'snippet' => search_excerpt($keys, $rendered, $item->langcode),
'langcode' => $entity->language()->getId(),
];
$this->addCacheableDependency($entity);
// We have to separately add the contact owner's cache tags because search
// module doesn't use the rendering system, it does its own rendering
// without taking cacheability metadata into account. So we have to do it
// explicitly here.
$this->addCacheableDependency($entity->getOwner());
// @codingStandardsIgnoreStart
// Uncomment this to display owner name and last changed time.
// $username = array(
// '#theme' => 'username',
// '#account' => $entity->getOwner(),
// );
// $result += array(
// 'user' => $this->renderer->renderPlain($username),
// 'date' => $entity->getChangedTime(),
// );
// @codingStandardsIgnoreEnd
$results[] = $result;
}
return $results;
}
/**
* Removes results data from the build array.
*
* This information is being removed from the rendered entity that is used to
* build the search result snippet.
*
* @param array $build
* The build array.
*
* @return array
* The modified build array.
*/
public function removeFromSnippet(array $build) {
// Code to remove arbitrary data from $build goes here.
// Examples:
// - unset($build['created']);
// - unset($build['uid']);.
return $build;
}
/**
* Adds the configured rankings to the search query.
*
* @param \Drupal\Core\Database\Query\SelectExtender $query
* A query object that has been extended with the Search DB Extender.
*/
protected function addFedoraResourceRankings(SelectExtender $query) {
if ($ranking = $this->getRankings()) {
$tables = &$query->getTables();
foreach ($ranking as $rank => $values) {
if (isset($this->configuration['rankings'][$rank]) && !empty($this->configuration['rankings'][$rank])) {
$entity_rank = $this->configuration['rankings'][$rank];
// If the table defined in the ranking isn't already joined, add it.
if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
$query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
}
$arguments = isset($values['arguments']) ? $values['arguments'] : [];
$query->addScore($values['score'], $arguments, $entity_rank);
}
}
}
}
/**
* {@inheritdoc}
*/
public function updateIndex() {
// Interpret the cron limit setting as the maximum number of entities to
// index per cron run.
$limit = (int) $this->searchSettings->get('index.cron_limit');
$result = $this->database->queryRange("SELECT c.id, MAX(sd.reindex) FROM {fedora_resource} c LEFT JOIN {search_dataset} sd ON sd.sid = c.id AND sd.type = :type WHERE sd.sid IS NULL OR sd.reindex <> 0 GROUP BY c.id ORDER BY MAX(sd.reindex) is null DESC, MAX(sd.reindex) ASC, c.id ASC", 0, $limit, [':type' => $this->getPluginId()], ['target' => 'replica']);
$rids = $result->fetchCol();
if (!$rids) {
return;
}
// 'fedora_resource' comes from the entity type id declared
// in the annotation for \Drupal\islandora\Entity\FedoraResource.
// Replace this with your entity's type id.
$entity_storage = $this->entityManager->getStorage('fedora_resource');
foreach ($entity_storage->loadMultiple($rids) as $entity) {
$this->indexFedoraResource($entity);
}
}
/**
* Indexes a single contact.
*
* @param \Drupal\islandora\FedoraResourceInterface $entity
* The contact to index.
*/
protected function indexFedoraResource(FedoraResourceInterface $entity) {
$languages = $entity->getTranslationLanguages();
// 'content_entity_example_contact' comes from the entity type id declared
// in the annotation for \Drupal\content_entity_example\Entity\Contact.
// Replace this with your entity's type id.
$entity_render = $this->entityManager->getViewBuilder('fedora_resource');
foreach ($languages as $language) {
$entity = $entity->getTranslation($language->getId());
// Render the contact.
$build = $entity_render->view($entity, 'search_index', $language->getId());
unset($build['#theme']);
// Add the title to text so it is searchable.
$build['search_title'] = [
'#prefix' => '',
'#plain_text' => $entity->label(),
'#suffix' => '',
'#weight' => -1000,
];
$text = $this->renderer->renderPlain($build);
// Fetch extra data normally not visible.
$extra = $this->moduleHandler->invokeAll('fedora_resource_update_index', [$entity]);
foreach ($extra as $t) {
$text .= $t;
}
// Update index, using search index "type" equal to the plugin ID.
search_index($this->getPluginId(), $entity->id(), $language->getId(), $text);
}
}
/**
* {@inheritdoc}
*/
public function indexClear() {
// All ContactSearch pages share a common search index "type" equal to
// the plugin ID.
search_index_clear($this->getPluginId());
}
/**
* {@inheritdoc}
*/
public function markForReindex() {
// All ContactSearch pages share a common search index "type" equal to
// the plugin ID.
search_mark_for_reindex($this->getPluginId());
}
/**
* {@inheritdoc}
*/
public function indexStatus() {
$total = $this->database->query('SELECT COUNT(*) FROM {fedora_resource}')->fetchField();
$remaining = $this->database->query("SELECT COUNT(DISTINCT c.id) FROM {contact} c LEFT JOIN {search_dataset} sd ON sd.sid = c.id AND sd.type = :type WHERE sd.sid IS NULL OR sd.reindex <> 0", [':type' => $this->getPluginId()])->fetchField();
return ['remaining' => $remaining, 'total' => $total];
}
/**
* {@inheritdoc}
*/
public function searchFormAlter(array &$form, FormStateInterface $form_state) {
$parameters = $this->getParameters();
$keys = $this->getKeywords();
$used_advanced = !empty($parameters[self::ADVANCED_FORM]);
if ($used_advanced) {
$f = isset($parameters['f']) ? (array) $parameters['f'] : [];
$defaults = $this->parseAdvancedDefaults($f, $keys);
}
else {
$defaults = ['keys' => $keys];
}
$form['basic']['keys']['#default_value'] = $defaults['keys'];
// Add advanced search keyword-related boxes.
$form['advanced'] = [
'#type' => 'details',
'#title' => t('Advanced search'),
'#attributes' => ['class' => ['search-advanced']],
'#access' => $this->account && $this->account->hasPermission('use advanced search'),
'#open' => $used_advanced,
];
$form['advanced']['keywords-fieldset'] = [
'#type' => 'fieldset',
'#title' => t('Keywords'),
];
$form['advanced']['keywords-fieldset']['keywords']['or'] = [
'#type' => 'textfield',
'#title' => t('Containing any of the words'),
'#size' => 30,
'#maxlength' => 255,
'#default_value' => isset($defaults['or']) ? $defaults['or'] : '',
];
$form['advanced']['keywords-fieldset']['keywords']['phrase'] = [
'#type' => 'textfield',
'#title' => t('Containing the phrase'),
'#size' => 30,
'#maxlength' => 255,
'#default_value' => isset($defaults['phrase']) ? $defaults['phrase'] : '',
];
$form['advanced']['keywords-fieldset']['keywords']['negative'] = [
'#type' => 'textfield',
'#title' => t('Containing none of the words'),
'#size' => 30,
'#maxlength' => 255,
'#default_value' => isset($defaults['negative']) ? $defaults['negative'] : '',
];
$form['advanced']['misc-fieldset'] = [
'#type' => 'fieldset',
];
// \Drupal\search\SearchQuery requires that there be valid keywords
// submitted in the standard fields.
$form['advanced']['misc-fieldset']['note'] = [
'#markup' => t('You must still enter keyword(s) above when using these fields.'),
'#weight' => -10,
];
$form['advanced']['misc-fieldset']['name'] = [
'#type' => 'textfield',
'#title' => t('Name'),
'#description' => t('Search %field field for exact matches.', ['%field' => 'Name']),
'#default_value' => isset($defaults['name']) ? $defaults['name'] : [],
];
$form['advanced']['submit'] = [
'#type' => 'submit',
'#value' => t('Advanced search'),
'#prefix' => '',
'#suffix' => '',
'#weight' => 100,
];
}
/**
* {@inheritdoc}
*/
public function buildSearchUrlQuery(FormStateInterface $form_state) {
// Read keyword and advanced search information from the form values,
// and put these into the GET parameters.
$keys = trim($form_state->getValue('keys'));
$advanced = FALSE;
// Collect extra filters.
$filters = [];
// Advanced form, custom_content_entity_example_contact fields.
if ($form_state->hasValue('name') && !empty(($value = trim($form_state->getValue('name'))))) {
$filters[] = 'name:' . $value;
$advanced = TRUE;
}
// Advanced form, keywords fields.
if ($form_state->getValue('or') != '') {
if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state->getValue('or'), $matches)) {
$keys .= ' ' . implode(' OR ', $matches[1]);
$advanced = TRUE;
}
}
if ($form_state->getValue('negative') != '') {
if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state->getValue('negative'), $matches)) {
$keys .= ' -' . implode(' -', $matches[1]);
$advanced = TRUE;
}
}
if ($form_state->getValue('phrase') != '') {
$keys .= ' "' . str_replace('"', ' ', $form_state->getValue('phrase')) . '"';
$advanced = TRUE;
}
$keys = trim($keys);
// Put the keywords and advanced parameters into GET parameters. Make sure
// to put keywords into the query even if it is empty, because the page
// controller uses that to decide it's time to check for search results.
$query = ['keys' => $keys];
if ($filters) {
$query['f'] = $filters;
}
// Record that the person used the advanced search form, if they did.
if ($advanced) {
$query[self::ADVANCED_FORM] = '1';
}
return $query;
}
/**
* Parses the advanced search form default values.
*
* @param array $f
* The 'f' query parameter set up in self::buildUrlSearchQuery(), which
* contains the advanced query values.
* @param string $keys
* The search keywords string, which contains some information from the
* advanced search form.
*
* @return array
* Array of default form values for the advanced search form, including
* a modified 'keys' element for the bare search keywords.
*/
protected function parseAdvancedDefaults(array $f, $keys) {
$defaults = [];
// Split out the advanced search parameters.
foreach ($f as $advanced) {
list($key, $value) = explode(':', $advanced, 2);
if (!isset($defaults[$key])) {
$defaults[$key] = [];
}
$defaults[$key][] = $value;
}
// Split out the negative, phrase, and OR parts of keywords.
// For phrases, the form only supports one phrase.
$matches = [];
$keys = ' ' . $keys . ' ';
if (preg_match('/ "([^"]+)" /', $keys, $matches)) {
$keys = str_replace($matches[0], ' ', $keys);
$defaults['phrase'] = $matches[1];
}
// Negative keywords: pull all of them out.
if (preg_match_all('/ -([^ ]+)/', $keys, $matches)) {
$keys = str_replace($matches[0], ' ', $keys);
$defaults['negative'] = implode(' ', $matches[1]);
}
// OR keywords: pull up to one set of them out of the query.
if (preg_match('/ [^ ]+( OR [^ ]+)+ /', $keys, $matches)) {
$keys = str_replace($matches[0], ' ', $keys);
$words = explode(' OR ', trim($matches[0]));
$defaults['or'] = implode(' ', $words);
}
// Put remaining keywords string back into keywords.
$defaults['keys'] = trim($keys);
return $defaults;
}
/**
* Gathers ranking definitions from hook_ranking().
*
* @return array
* An array of ranking definitions.
*/
protected function getRankings() {
if (!$this->rankings) {
$this->rankings = $this->moduleHandler->invokeAll('ranking');
}
return $this->rankings;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
$configuration = [
'rankings' => [],
];
return $configuration;
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
// Output form for defining rank factor weights.
$form['content_ranking'] = [
'#type' => 'details',
'#title' => t('Content ranking'),
'#open' => TRUE,
];
$form['content_ranking']['info'] = [
'#markup' => '' . $this->t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '',
];
// Prepare table.
$header = [$this->t('Factor'), $this->t('Influence')];
$form['content_ranking']['rankings'] = [
'#type' => 'table',
'#header' => $header,
];
// Note: reversed to reflect that higher number = higher ranking.
$range = range(0, 10);
$options = array_combine($range, $range);
foreach ($this->getRankings() as $var => $values) {
$form['content_ranking']['rankings'][$var]['name'] = [
'#markup' => $values['title'],
];
$form['content_ranking']['rankings'][$var]['value'] = [
'#type' => 'select',
'#options' => $options,
'#attributes' => ['aria-label' => $this->t("Influence of '@title'", ['@title' => $values['title']])],
'#default_value' => isset($this->configuration['rankings'][$var]) ? $this->configuration['rankings'][$var] : 0,
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
foreach ($this->getRankings() as $var => $values) {
if (!$form_state->isValueEmpty(['rankings', $var, 'value'])) {
$this->configuration['rankings'][$var]
= $form_state->getValue(['rankings', $var, 'value']);
}
else {
unset($this->configuration['rankings'][$var]);
}
}
}
}

130
src/Plugin/views/wizard/FedoraResource.php

@ -1,130 +0,0 @@
<?php
namespace Drupal\islandora\Plugin\views\wizard;
use Drupal\views\Plugin\views\wizard\WizardPluginBase;
/**
* Tests creating node views with the wizard.
*
* Mostly copied from Nodes wizard, look there for more options.
*
* @ViewsWizard(
* id = "fedora_resource",
* base_table = "fedora_resource_field_data",
* title = @Translation("Fedora Resource")
* )
*/
class FedoraResource extends WizardPluginBase {
/**
* Set the created column.
*
* @var string
*/
protected $createdColumn = 'fedora_resource_field_data-created';
/**
* Override base method.
*
* Drupal\views\Plugin\views\wizard\WizardPluginBase::getAvailableSorts().
*
* @return array
* An array whose keys are the available sort options and whose
* corresponding values are human readable labels.
*/
public function getAvailableSorts() {
// You can't execute functions in properties, so override the method.
return [
'fedora_resource_field_data-name:ASC' => $this->t('Name'),
];
}
/**
* {@inheritdoc}
*/
protected function defaultDisplayOptions() {
$display_options = parent::defaultDisplayOptions();
// Add permission-based access control.
$display_options['access']['type'] = 'perm';
$display_options['access']['options']['perm'] = 'access content';
// Remove the default fields, since we are customizing them here.
unset($display_options['fields']);
// Add the title field, so that the display has content if the user switches
// to a row style that uses fields.
/* Field: Content: Title */
$display_options['fields']['name']['id'] = 'name';
$display_options['fields']['name']['table'] = 'fedora_resource_field_data';
$display_options['fields']['name']['field'] = 'name';
$display_options['fields']['name']['entity_type'] = 'fedora_resource';
$display_options['fields']['name']['entity_field'] = 'name';
$display_options['fields']['name']['label'] = '';
$display_options['fields']['name']['alter']['alter_text'] = 0;
$display_options['fields']['name']['alter']['make_link'] = 0;
$display_options['fields']['name']['alter']['absolute'] = 0;
$display_options['fields']['name']['alter']['trim'] = 0;
$display_options['fields']['name']['alter']['word_boundary'] = 0;
$display_options['fields']['name']['alter']['ellipsis'] = 0;
$display_options['fields']['name']['alter']['strip_tags'] = 0;
$display_options['fields']['name']['alter']['html'] = 0;
$display_options['fields']['name']['hide_empty'] = 0;
$display_options['fields']['name']['empty_zero'] = 0;
$display_options['fields']['name']['settings']['link_to_entity'] = 1;
$display_options['fields']['name']['plugin_id'] = 'field';
return $display_options;
}
/**
* {@inheritdoc}
*/
protected function pageDisplayOptions(array $form, FormStateInterface $form_state) {
$display_options = parent::pageDisplayOptions($form, $form_state);
$row_plugin = $form_state->getValue(['page', 'style', 'row_plugin']);
$row_options = $form_state->getValue(['page', 'style', 'row_options'], []);
$this->display_options_row($display_options, $row_plugin, $row_options);
return $display_options;
}
/**
* {@inheritdoc}
*/
protected function blockDisplayOptions(array $form, FormStateInterface $form_state) {
$display_options = parent::blockDisplayOptions($form, $form_state);
$row_plugin = $form_state->getValue(['block', 'style', 'row_plugin']);
$row_options = $form_state->getValue(['block', 'style', 'row_options'], []);
$this->displayOptionsRow($display_options, $row_plugin, $row_options);
return $display_options;
}
/**
* Set the row style and row style plugins to the display_options.
*/
protected function displayOptionsRow(&$display_options, $row_plugin, $row_options) {
switch ($row_plugin) {
case 'full_posts':
$display_options['row']['type'] = 'entity:fedora_resource';
$display_options['row']['options']['view_mode'] = 'full';
break;
case 'teasers':
$display_options['row']['type'] = 'entity:fedora_resource';
$display_options['row']['options']['view_mode'] = 'teaser';
break;
case 'titles_linked':
case 'titles':
$display_options['row']['type'] = 'fields';
$display_options['fields']['title']['id'] = 'title';
$display_options['fields']['title']['table'] = 'fedora_resource_field_data';
$display_options['fields']['title']['field'] = 'title';
$display_options['fields']['title']['settings']['link_to_entity'] = $row_plugin === 'titles_linked';
$display_options['fields']['title']['plugin_id'] = 'field';
break;
}
}
}

36
src/Tests/Web/JsonldContextGeneratorWebTest.php

@ -3,7 +3,7 @@
namespace Drupal\islandora\Tests\Web;
use Drupal\Core\Url;
use Drupal\islandora\Entity\FedoraResourceType;
use Drupal\node\Entity\NodeType;
use Drupal\rdf\Entity\RdfMapping;
/**
@ -33,33 +33,31 @@ class JsonldContextGeneratorWebTest extends IslandoraWebTestBase {
public function setUp() {
parent::setUp();
// Create a bundle to test.
$rdf_source = FedoraResourceType::create([
'id' => 'rdf_source',
'label' => 'RdfSource',
$test_type = NodeType::create([
'type' => 'test_type',
'label' => 'Test Type',
]);
$rdf_source->save();
$test_type->save();
// Give it a basic rdf mapping.
$rdf_source_mapping = RdfMapping::create([
'id' => 'fedora_resourcce.rdf_source',
'targetEntityType' => 'fedora_resource',
'bundle' => 'rdf_source',
$mapping = RdfMapping::create([
'id' => 'node.test_type',
'targetEntityType' => 'node',
'bundle' => 'test_type',
'types' => ['schema:Thing'],
'fieldMappings' => [
'name' => [
'title' => [
'properties' => ['dc11:title'],
],
],
]);
$rdf_source_mapping->save();
$mapping->save();
$this->user = $this->drupalCreateUser([
'administer site configuration',
'view published fedora resource entities',
'access content',
]
);
'administer nodes',
]);
// Login.
$this->drupalLogin($this->user);
}
@ -68,7 +66,7 @@ class JsonldContextGeneratorWebTest extends IslandoraWebTestBase {
* Tests that the Context Response Page can be reached.
*/
public function testJsonldcontextPageExists() {
$url = Url::fromRoute('entity.fedora_resource_type.jsonldcontext', ['bundle' => 'rdf_source']);
$url = Url::fromRoute('islandora.jsonldcontext', ['entity_type' => 'node', 'bundle' => 'test_type']);
$this->drupalGet($url);
$this->assertResponse(200);
}
@ -77,7 +75,7 @@ class JsonldContextGeneratorWebTest extends IslandoraWebTestBase {
* Tests that the response is in fact application/ld+json.
*/
public function testJsonldcontextContentypeheaderResponseIsValid() {
$url = Url::fromRoute('entity.fedora_resource_type.jsonldcontext', ['bundle' => 'rdf_source']);
$url = Url::fromRoute('islandora.jsonldcontext', ['entity_type' => 'node', 'bundle' => 'test_type']);
$this->drupalGet($url);
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/ld+json', 'Correct JSON-LD mime type was returned');
}
@ -86,7 +84,7 @@ class JsonldContextGeneratorWebTest extends IslandoraWebTestBase {
* Tests that the Context received has the basic structural needs.
*/
public function testJsonldcontextResponseIsValid() {
$url = Url::fromRoute('entity.fedora_resource_type.jsonldcontext', ['bundle' => 'rdf_source']);
$url = Url::fromRoute('islandora.jsonldcontext', ['entity_type' => 'node', 'bundle' => 'test_type']);
$this->drupalGet($url);
$jsonldarray = json_decode($this->getRawContent(), TRUE);
// Check if the only key is "@context".

23
templates/fedora-resource-content-add-list.html.twig

@ -1,23 +0,0 @@
{#
/**
* @file
* Default theme implementation to present a list of custom content entity types/bundles.
*
* Available variables:
* - types: A collection of all the available custom entity types/bundles.
* Each type/bundle contains the following:
* - link: A link to add a content entity of this type.
* - description: A description of this content entity types/bundle.
*
* @see template_preprocess_fedora_resource_content_add_list()
*
* @ingroup themeable
*/
#}
{% spaceless %}
<dl>
{% for type in types %}
<dt>{{ type.link }}</dt>
{% endfor %}
</dl>
{% endspaceless %}

22
templates/fedora_resource.html.twig

@ -1,22 +0,0 @@
{#
/**
* @file fedora_resource.html.twig
* Default theme implementation to present Fedora resource data.
*
* This template is used when viewing Fedora resource pages.
*
*
* Available variables:
* - content: A list of content items. Use 'content' to print all content, or
* - attributes: HTML attributes for the container element.
*
* @see template_preprocess_fedora_resource()
*
* @ingroup themeable
*/
#}
<div{{ attributes.addClass('fedora_resource') }}>
{% if content %}
{{- content -}}
{% endif %}
</div>

92
tests/src/Kernel/DeleteFedoraResourceWithParentsTest.php

@ -1,92 +0,0 @@
<?php
namespace Drupal\Tests\islandora\Kernel;
use Drupal\islandora\Entity\FedoraResource;
use Drupal\simpletest\UserCreationTrait;
/**
* Tests the clean up of deleted parent referenced from children.
*
* @group islandora
* @coversDefaultClass \Drupal\islandora\Entity\FedoraResource
*/
class DeleteFedoraResourceWithParentsTest extends IslandoraKernelTestBase {
use UserCreationTrait;
/**
* Parent Fedora resource entity.
*
* @var \Drupal\islandora\FedoraResourceInterface
*/
protected $parentEntity;
/**
* Child Fedora resource entity.
*
* @var \Drupal\islandora\FedoraResourceInterface
*/
protected $childEntity;
/**
* User entity.
*
* @var \Drupal\user\UserInterface
*/
protected $user;
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$permissions = [
'add fedora resource entities',
'edit fedora resource entities',
'delete fedora resource entities',
];
$this->assertTrue($this->checkPermissions($permissions), 'Permissions are invalid');
$this->user = $this->createUser($permissions);
// Create a test entity.
$this->parentEntity = FedoraResource::create([
"type" => "rdf_source",
"uid" => $this->user->get('uid'),
"name" => "Test Parent",
"langcode" => "und",
"status" => 1,
]);
$this->parentEntity->save();
$this->childEntity = FedoraResource::create([
"type" => "rdf_source",
"uid" => $this->user->get('uid'),
"name" => "Test Child",
"langcode" => "und",
"fedora_has_parent" => $this->parentEntity,
"status" => 1,
]);
$this->childEntity->save();
}
/**
* Tests cleaning up child to parent references when parent is deleted.
*
* @covers \Drupal\islandora\Entity\FedoraResource::postDelete
*/
public function testCleanUpParents() {
$child_id = $this->childEntity->id();
// Load the child entity.
$new_child = FedoraResource::load($child_id);
// Verify it has a parent.
$this->assertFalse($new_child->get('fedora_has_parent')->isEmpty(), "Should have a parent.");
// Delete the parent entity.
$this->parentEntity->delete();
// Verify we don't have a parent anymore.
$this->assertTrue($new_child->get('fedora_has_parent')->isEmpty(), "Should not have a parent.");
}
}

17
tests/src/Kernel/EventGeneratorTestBase.php

@ -2,7 +2,8 @@
namespace Drupal\Tests\islandora\Kernel;
use Drupal\islandora\Entity\FedoraResource;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\simpletest\UserCreationTrait;
/**
@ -22,7 +23,7 @@ abstract class EventGeneratorTestBase extends IslandoraKernelTestBase {
/**
* Fedora resource entity.
*
* @var \Drupal\islandora\FedoraResourceInterface
* @var \Drupal\node\Entity\NodeInterface
*/
protected $entity;
@ -35,11 +36,17 @@ abstract class EventGeneratorTestBase extends IslandoraKernelTestBase {
// Create a test user.
$this->user = $this->createUser(['add fedora resource entities']);
$test_type = NodeType::create([
'type' => 'test_type',
'label' => 'Test Type',
]);
$test_type->save();
// Create a test entity.
$this->entity = FedoraResource::create([
"type" => "rdf_source",
$this->entity = Node::create([
"type" => "test_type",
"uid" => $this->user->get('uid'),
"name" => "Test Fixture",
"title" => "Test Fixture",
"langcode" => "und",
"status" => 1,
]);

43
tests/src/Kernel/FedoraContentTypeCreationTrait.php

@ -1,43 +0,0 @@
<?php
namespace Drupal\Tests\islandora\Kernel;
use Drupal\Component\Utility\Random;
use Drupal\islandora\Entity\FedoraResourceType;
/**
* Trait that aids in the creation of a fedora resource type bundle.
*/
trait FedoraContentTypeCreationTrait {
/**
* Creates a custom content Fedora Resource type based on default settings.
*
* @param array $values
* An array of settings to change from the defaults.
* Example: 'id' => 'some_bundle'.
*
* @return \Drupal\islandora\Entity\FedoraResourceType
* Created content type.
*/
protected function createFedoraResourceContentType(array $values = []) {
// Find a non-existent random type name.
$random = new Random();
if (!isset($values['type'])) {
do {
$id = strtolower($random->string(8));
} while (FedoraResourceType::load($id));
}
else {
$id = $values['type'];
}
$values += [
'id' => $id,
'label' => $id,
];
$type = FedoraResourceType::create($values);
$type->save();
return $type;
}
}

134
tests/src/Kernel/FedoraResourceParentTest.php

@ -1,134 +0,0 @@
<?php
namespace Drupal\Tests\islandora\Kernel;
use Drupal\islandora\Entity\FedoraResource;
use Drupal\simpletest\UserCreationTrait;
/**
* Tests for adding, removing and testing for parents.
*
* @group islandora
* @coversDefaultClass \Drupal\islandora\Entity\FedoraResource
*/
class FedoraResourceParentTest extends IslandoraKernelTestBase {
use UserCreationTrait;
/**
* A Drupal user.
*
* @var \Drupal\user\UserInterface
*/
protected $user;
/**
* A Fedora Resource.
*
* @var \Drupal\islandora\Entity\FedoraResource
*/
protected $entity;
/**
* Another Fedora Resource.
*
* @var \Drupal\islandora\Entity\FedoraResource
*/
protected $parentEntity;
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$permissions = [
'add fedora resource entities',
'edit fedora resource entities',
'delete fedora resource entities',
];
$this->assertTrue($this->checkPermissions($permissions), 'Permissions are invalid');
$this->user = $this->createUser($permissions);
$this->entity = FedoraResource::create([
'type' => 'rdf_source',
'uid' => $this->user->get('uid'),
'name' => 'Test Entity',
'langcode' => 'und',
'status' => 1,
]);
$this->entity->save();
$this->parentEntity = FedoraResource::create([
'type' => 'rdf_source',
'uid' => $this->user->get('uid'),
'name' => 'Parent Entity',
'langcode' => 'und',
'status' => 1,
]);
$this->parentEntity->save();
}
/**
* @covers \Drupal\islandora\Entity\FedoraResource::setParent
*/
public function testSetParent() {
$this->assertTrue($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has an unexpected parent.");
$this->entity->setParent($this->parentEntity);
$this->entity->save();
$this->assertFalse($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has no parent.");
}
/**
* @covers \Drupal\islandora\Entity\FedoraResource::removeParent
*/
public function testRemoveParent() {
$this->assertTrue($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has an unexpected parent.");
$this->entity->set('fedora_has_parent', $this->parentEntity);
$this->entity->save();
$this->assertFalse($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has no parent.");
$this->entity->removeParent();
$this->entity->save();
$this->assertTrue($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has an unexpected parent.");
}
/**
* @covers \Drupal\islandora\Entity\FedoraResource::hasParent
*/
public function testHasParent() {
$this->assertTrue($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has an unexpected parent.");
$this->assertFalse($this->entity->hasParent(), "hasParent is reporting a parent incorrectly.");
$this->entity->set('fedora_has_parent', $this->parentEntity);
$this->entity->save();
$this->assertFalse($this->entity->get('fedora_has_parent')->isEmpty(), "Entity has no parent.");
$this->assertTrue($this->entity->hasParent(), "hasParent is reporting NO parent incorrectly.");
$this->entity->set('fedora_has_parent', NULL);
$this->entity->save();
$this->assertTrue($this->entity->get('fedora_has_parent')->isEmpty(), "Entity still has a parent.");
$this->assertFalse($this->entity->hasParent(), "hasParent is reporting a parent incorrectly.");
}
/**
* @covers \Drupal\islandora\Entity\FedoraResource::getParentId
*/
public function testGetParentId() {
$id = $this->parentEntity->id();
$this->entity->set('fedora_has_parent', $this->parentEntity);
$this->entity->save();
$this->assertEquals($id, $this->entity->getParentId(), "Did not get correct parent id.");
}
}

3
tests/src/Kernel/IslandoraKernelTestBase.php

@ -49,10 +49,11 @@ abstract class IslandoraKernelTestBase extends KernelTestBase {
// Bootstrap minimal Drupal environment to run the tests.
$this->installSchema('system', 'sequences');
$this->installSchema('node', 'node_access');
$this->installEntitySchema('user');
$this->installEntitySchema('node');
$this->installConfig('filter');
$this->installSchema('islandora', 'islandora_version_count');
$this->installEntitySchema('fedora_resource');
}
}

23
tests/src/Kernel/VersionCounterTest.php

@ -2,14 +2,15 @@
namespace Drupal\Tests\islandora\Kernel;
use Drupal\islandora\Entity\FedoraResource;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\simpletest\UserCreationTrait;
/**
* Tests the basic behavior of a vector clock.
*
* @group islandora
* @coversDefaultClass \Drupal\islandora\Entity\FedoraResource
* @coversDefaultClass \Drupal\islandora\VersionCounter\VersionCounter
*/
class VersionCounterTest extends IslandoraKernelTestBase {
@ -18,7 +19,7 @@ class VersionCounterTest extends IslandoraKernelTestBase {
/**
* Fedora resource entity.
*
* @var \Drupal\islandora\FedoraResourceInterface
* @var \Drupal\node\Entity\NodeInterface
*/
protected $entity;
@ -36,13 +37,19 @@ class VersionCounterTest extends IslandoraKernelTestBase {
parent::setUp();
// Create a test user.
$this->user = $this->createUser(['add fedora resource entities', 'edit fedora resource entities']);
$this->user = $this->createUser(['administer nodes']);
$test_type = NodeType::create([
'type' => 'test_type',
'label' => 'Test Type',
]);
$test_type->save();
// Create a test entity.
$this->entity = FedoraResource::create([
"type" => "rdf_source",
$this->entity = Node::create([
"type" => "test_type",
"uid" => $this->user->get('uid'),
"name" => "Test Fixture",
"title" => "Test Fixture",
"langcode" => "und",
"status" => 1,
]);
@ -75,7 +82,7 @@ class VersionCounterTest extends IslandoraKernelTestBase {
* @covers \Drupal\islandora\VersionCounter\VersionCounter::get
*/
public function testRecordIncrementsOnUpdate() {
$this->entity->setName("New Name");
$this->entity->setTitle("New Title");
$this->entity->save();
$versionCounter = $this->container->get('islandora.versioncounter');

Loading…
Cancel
Save