clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,76 @@
langcode: en
status: true
dependencies:
module:
- system
id: action--action
disabled: true
path: action/action
resourceType: action--action
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
type:
fieldName: type
publicName: type
enhancer:
id: ''
disabled: false
plugin:
fieldName: plugin
publicName: plugin
enhancer:
id: ''
disabled: false
configuration:
fieldName: configuration
publicName: configuration
enhancer:
id: ''
disabled: false
@@ -0,0 +1,116 @@
langcode: en
status: true
dependencies: { }
id: base_field_override--base_field_override
disabled: true
path: base_field_override/base_field_override
resourceType: base_field_override--base_field_override
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
field_name:
fieldName: field_name
publicName: field_name
enhancer:
id: ''
disabled: false
entity_type:
fieldName: entity_type
publicName: entity_type
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
required:
fieldName: required
publicName: required
enhancer:
id: ''
disabled: false
translatable:
fieldName: translatable
publicName: translatable
enhancer:
id: ''
disabled: false
default_value:
fieldName: default_value
publicName: default_value
enhancer:
id: ''
disabled: false
default_value_callback:
fieldName: default_value_callback
publicName: default_value_callback
enhancer:
id: ''
disabled: false
settings:
fieldName: settings
publicName: settings
enhancer:
id: ''
disabled: false
field_type:
fieldName: field_type
publicName: field_type
enhancer:
id: ''
disabled: false
@@ -0,0 +1,94 @@
langcode: en
status: true
dependencies:
module:
- block
id: block--block
disabled: true
path: block/block
resourceType: block--block
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
theme:
fieldName: theme
publicName: theme
enhancer:
id: ''
disabled: false
region:
fieldName: region
publicName: region
enhancer:
id: ''
disabled: false
weight:
fieldName: weight
publicName: weight
enhancer:
id: ''
disabled: false
provider:
fieldName: provider
publicName: provider
enhancer:
id: ''
disabled: false
plugin:
fieldName: plugin
publicName: plugin
enhancer:
id: ''
disabled: false
settings:
fieldName: settings
publicName: settings
enhancer:
id: ''
disabled: false
visibility:
fieldName: visibility
publicName: visibility
enhancer:
id: ''
disabled: false
@@ -0,0 +1,130 @@
langcode: en
status: true
dependencies:
module:
- consumers
id: consumer--consumer
disabled: true
path: consumer/consumer
resourceType: consumer--consumer
resourceFields:
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
owner_id:
fieldName: owner_id
publicName: owner_id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
image:
fieldName: image
publicName: image
enhancer:
id: ''
disabled: false
third_party:
fieldName: third_party
publicName: third_party
enhancer:
id: ''
disabled: false
is_default:
fieldName: is_default
publicName: is_default
enhancer:
id: ''
disabled: false
default_langcode:
fieldName: default_langcode
publicName: default_langcode
enhancer:
id: ''
disabled: false
secret:
fieldName: secret
publicName: secret
enhancer:
id: ''
disabled: false
confidential:
fieldName: confidential
publicName: confidential
enhancer:
id: ''
disabled: false
roles:
fieldName: roles
publicName: roles
enhancer:
id: ''
disabled: false
redirect:
fieldName: redirect
publicName: redirect
enhancer:
id: ''
disabled: false
user_id:
fieldName: user_id
publicName: user_id
enhancer:
id: ''
disabled: false
pkce:
fieldName: pkce
publicName: pkce
enhancer:
id: ''
disabled: false
client_id:
fieldName: client_id
publicName: client_id
enhancer:
id: ''
disabled: false
grant_user_access:
fieldName: grant_user_access
publicName: grant_user_access
enhancer:
id: ''
disabled: false
limit_requested_access:
fieldName: limit_requested_access
publicName: limit_requested_access
enhancer:
id: ''
disabled: false
limit_user_access:
fieldName: limit_user_access
publicName: limit_user_access
enhancer:
id: ''
disabled: false
@@ -0,0 +1,68 @@
langcode: en
status: true
dependencies: { }
id: date_format--date_format
disabled: true
path: date_format/date_format
resourceType: date_format--date_format
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
locked:
fieldName: locked
publicName: locked
enhancer:
id: ''
disabled: false
pattern:
fieldName: pattern
publicName: pattern
enhancer:
id: ''
disabled: false
@@ -0,0 +1,80 @@
langcode: en
status: true
dependencies: { }
id: entity_form_display--entity_form_display
disabled: true
path: entity_form_display/entity_form_display
resourceType: entity_form_display--entity_form_display
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
targetEntityType:
fieldName: targetEntityType
publicName: targetEntityType
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
mode:
fieldName: mode
publicName: mode
enhancer:
id: ''
disabled: false
content:
fieldName: content
publicName: content
enhancer:
id: ''
disabled: false
hidden:
fieldName: hidden
publicName: hidden
enhancer:
id: ''
disabled: false
@@ -0,0 +1,68 @@
langcode: en
status: true
dependencies: { }
id: entity_form_mode--entity_form_mode
disabled: true
path: entity_form_mode/entity_form_mode
resourceType: entity_form_mode--entity_form_mode
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
targetEntityType:
fieldName: targetEntityType
publicName: targetEntityType
enhancer:
id: ''
disabled: false
cache:
fieldName: cache
publicName: cache
enhancer:
id: ''
disabled: false
@@ -0,0 +1,80 @@
langcode: en
status: true
dependencies: { }
id: entity_view_display--entity_view_display
disabled: true
path: entity_view_display/entity_view_display
resourceType: entity_view_display--entity_view_display
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
targetEntityType:
fieldName: targetEntityType
publicName: targetEntityType
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
mode:
fieldName: mode
publicName: mode
enhancer:
id: ''
disabled: false
content:
fieldName: content
publicName: content
enhancer:
id: ''
disabled: false
hidden:
fieldName: hidden
publicName: hidden
enhancer:
id: ''
disabled: false
@@ -0,0 +1,68 @@
langcode: en
status: true
dependencies: { }
id: entity_view_mode--entity_view_mode
disabled: true
path: entity_view_mode/entity_view_mode
resourceType: entity_view_mode--entity_view_mode
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
targetEntityType:
fieldName: targetEntityType
publicName: targetEntityType
enhancer:
id: ''
disabled: false
cache:
fieldName: cache
publicName: cache
enhancer:
id: ''
disabled: false
@@ -0,0 +1,118 @@
langcode: en
status: true
dependencies:
module:
- field
id: field_config--field_config
disabled: true
path: field_config/field_config
resourceType: field_config--field_config
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
field_name:
fieldName: field_name
publicName: field_name
enhancer:
id: ''
disabled: false
entity_type:
fieldName: entity_type
publicName: entity_type
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
required:
fieldName: required
publicName: required
enhancer:
id: ''
disabled: false
translatable:
fieldName: translatable
publicName: translatable
enhancer:
id: ''
disabled: false
default_value:
fieldName: default_value
publicName: default_value
enhancer:
id: ''
disabled: false
default_value_callback:
fieldName: default_value_callback
publicName: default_value_callback
enhancer:
id: ''
disabled: false
settings:
fieldName: settings
publicName: settings
enhancer:
id: ''
disabled: false
field_type:
fieldName: field_type
publicName: field_type
enhancer:
id: ''
disabled: false
@@ -0,0 +1,118 @@
langcode: en
status: true
dependencies:
module:
- field
id: field_storage_config--field_storage_config
disabled: true
path: field_storage_config/field_storage_config
resourceType: field_storage_config--field_storage_config
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
field_name:
fieldName: field_name
publicName: field_name
enhancer:
id: ''
disabled: false
entity_type:
fieldName: entity_type
publicName: entity_type
enhancer:
id: ''
disabled: false
type:
fieldName: type
publicName: type
enhancer:
id: ''
disabled: false
settings:
fieldName: settings
publicName: settings
enhancer:
id: ''
disabled: false
module:
fieldName: module
publicName: module
enhancer:
id: ''
disabled: false
locked:
fieldName: locked
publicName: locked
enhancer:
id: ''
disabled: false
cardinality:
fieldName: cardinality
publicName: cardinality
enhancer:
id: ''
disabled: false
translatable:
fieldName: translatable
publicName: translatable
enhancer:
id: ''
disabled: false
indexes:
fieldName: indexes
publicName: indexes
enhancer:
id: ''
disabled: false
persist_with_no_fields:
fieldName: persist_with_no_fields
publicName: persist_with_no_fields
enhancer:
id: ''
disabled: false
custom_storage:
fieldName: custom_storage
publicName: custom_storage
enhancer:
id: ''
disabled: false
@@ -0,0 +1,76 @@
langcode: en
status: true
dependencies:
module:
- filter
id: filter_format--filter_format
disabled: true
path: filter_format/filter_format
resourceType: filter_format--filter_format
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
name:
fieldName: name
publicName: name
enhancer:
id: ''
disabled: false
format:
fieldName: format
publicName: format
enhancer:
id: ''
disabled: false
weight:
fieldName: weight
publicName: weight
enhancer:
id: ''
disabled: false
roles:
fieldName: roles
publicName: roles
enhancer:
id: ''
disabled: false
filters:
fieldName: filters
publicName: filters
enhancer:
id: ''
disabled: false
@@ -0,0 +1,64 @@
langcode: en
status: true
dependencies:
module:
- image
id: image_style--image_style
disabled: true
path: image_style/image_style
resourceType: image_style--image_style
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
name:
fieldName: name
publicName: name
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
effects:
fieldName: effects
publicName: effects
enhancer:
id: ''
disabled: false
@@ -0,0 +1,74 @@
langcode: en
status: true
dependencies: { }
id: jsonapi_resource_config--jsonapi_resource_config
disabled: true
path: jsonapi_resource_config/jsonapi_resource_config
resourceType: jsonapi_resource_config--jsonapi_resource_config
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
disabled:
fieldName: disabled
publicName: disabled
enhancer:
id: ''
disabled: false
path:
fieldName: path
publicName: path
enhancer:
id: ''
disabled: false
resourceType:
fieldName: resourceType
publicName: resourceType
enhancer:
id: ''
disabled: false
resourceFields:
fieldName: resourceFields
publicName: resourceFields
enhancer:
id: ''
disabled: false
@@ -0,0 +1,70 @@
langcode: en
status: true
dependencies:
module:
- system
id: menu--menu
disabled: true
path: menu/menu
resourceType: menu--menu
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
locked:
fieldName: locked
publicName: locked
enhancer:
id: ''
disabled: false
@@ -0,0 +1,112 @@
langcode: en
status: true
dependencies:
module:
- migrate_plus
id: migration--migration
disabled: true
path: migration/migration
resourceType: migration--migration
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
class:
fieldName: class
publicName: class
enhancer:
id: ''
disabled: false
field_plugin_method:
fieldName: field_plugin_method
publicName: field_plugin_method
enhancer:
id: ''
disabled: false
cck_plugin_method:
fieldName: cck_plugin_method
publicName: cck_plugin_method
enhancer:
id: ''
disabled: false
migration_tags:
fieldName: migration_tags
publicName: migration_tags
enhancer:
id: ''
disabled: false
migration_group:
fieldName: migration_group
publicName: migration_group
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
source:
fieldName: source
publicName: source
enhancer:
id: ''
disabled: false
process:
fieldName: process
publicName: process
enhancer:
id: ''
disabled: false
destination:
fieldName: destination
publicName: destination
enhancer:
id: ''
disabled: false
migration_dependencies:
fieldName: migration_dependencies
publicName: migration_dependencies
enhancer:
id: ''
disabled: false
@@ -0,0 +1,82 @@
langcode: en
status: true
dependencies:
module:
- migrate_plus
id: migration_group--migration_group
disabled: true
path: migration_group/migration_group
resourceType: migration_group--migration_group
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
source_type:
fieldName: source_type
publicName: source_type
enhancer:
id: ''
disabled: false
module:
fieldName: module
publicName: module
enhancer:
id: ''
disabled: false
shared_configuration:
fieldName: shared_configuration
publicName: shared_configuration
enhancer:
id: ''
disabled: false
@@ -0,0 +1,76 @@
langcode: en
status: true
dependencies:
config:
- simple_oauth.oauth2_token.bundle.access_token
id: oauth2_token--access_token
disabled: true
path: oauth2_token/access_token
resourceType: oauth2_token--access_token
resourceFields:
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
auth_user_id:
fieldName: auth_user_id
publicName: auth_user_id
enhancer:
id: ''
disabled: false
client:
fieldName: client
publicName: client
enhancer:
id: ''
disabled: false
scopes:
fieldName: scopes
publicName: scopes
enhancer:
id: ''
disabled: false
value:
fieldName: value
publicName: value
enhancer:
id: ''
disabled: false
created:
fieldName: created
publicName: created
enhancer:
id: ''
disabled: false
changed:
fieldName: changed
publicName: changed
enhancer:
id: ''
disabled: false
expire:
fieldName: expire
publicName: expire
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
@@ -0,0 +1,76 @@
langcode: en
status: true
dependencies:
config:
- simple_oauth.oauth2_token.bundle.auth_code
id: oauth2_token--auth_code
disabled: true
path: oauth2_token/auth_code
resourceType: oauth2_token--auth_code
resourceFields:
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
auth_user_id:
fieldName: auth_user_id
publicName: auth_user_id
enhancer:
id: ''
disabled: false
client:
fieldName: client
publicName: client
enhancer:
id: ''
disabled: false
scopes:
fieldName: scopes
publicName: scopes
enhancer:
id: ''
disabled: false
value:
fieldName: value
publicName: value
enhancer:
id: ''
disabled: false
created:
fieldName: created
publicName: created
enhancer:
id: ''
disabled: false
changed:
fieldName: changed
publicName: changed
enhancer:
id: ''
disabled: false
expire:
fieldName: expire
publicName: expire
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
@@ -0,0 +1,76 @@
langcode: en
status: true
dependencies:
config:
- simple_oauth.oauth2_token.bundle.refresh_token
id: oauth2_token--refresh_token
disabled: true
path: oauth2_token/refresh_token
resourceType: oauth2_token--refresh_token
resourceFields:
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
bundle:
fieldName: bundle
publicName: bundle
enhancer:
id: ''
disabled: false
auth_user_id:
fieldName: auth_user_id
publicName: auth_user_id
enhancer:
id: ''
disabled: false
client:
fieldName: client
publicName: client
enhancer:
id: ''
disabled: false
scopes:
fieldName: scopes
publicName: scopes
enhancer:
id: ''
disabled: false
value:
fieldName: value
publicName: value
enhancer:
id: ''
disabled: false
created:
fieldName: created
publicName: created
enhancer:
id: ''
disabled: false
changed:
fieldName: changed
publicName: changed
enhancer:
id: ''
disabled: false
expire:
fieldName: expire
publicName: expire
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
@@ -0,0 +1,70 @@
langcode: en
status: true
dependencies:
module:
- simple_oauth
id: oauth2_token_type--oauth2_token_type
disabled: true
path: oauth2_token_type/oauth2_token_type
resourceType: oauth2_token_type--oauth2_token_type
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
locked:
fieldName: locked
publicName: locked
enhancer:
id: ''
disabled: false
@@ -0,0 +1,58 @@
langcode: en
status: true
dependencies:
module:
- path_alias
id: path_alias--path_alias
disabled: true
path: path_alias/path_alias
resourceType: path_alias--path_alias
resourceFields:
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
revision_id:
fieldName: revision_id
publicName: revision_id
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
path:
fieldName: path
publicName: path
enhancer:
id: ''
disabled: false
alias:
fieldName: alias
publicName: alias
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
revision_default:
fieldName: revision_default
publicName: revision_default
enhancer:
id: ''
disabled: false
@@ -0,0 +1,70 @@
langcode: en
status: true
dependencies:
module:
- rest
id: rest_resource_config--rest_resource_config
disabled: true
path: rest_resource_config/rest_resource_config
resourceType: rest_resource_config--rest_resource_config
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
plugin_id:
fieldName: plugin_id
publicName: plugin_id
enhancer:
id: ''
disabled: false
granularity:
fieldName: granularity
publicName: granularity
enhancer:
id: ''
disabled: false
configuration:
fieldName: configuration
publicName: configuration
enhancer:
id: ''
disabled: false
@@ -0,0 +1,94 @@
langcode: en
status: true
dependencies:
module:
- views
id: view--view
disabled: true
path: view/view
resourceType: view--view
resourceFields:
uuid:
fieldName: uuid
publicName: uuid
enhancer:
id: ''
disabled: false
langcode:
fieldName: langcode
publicName: langcode
enhancer:
id: ''
disabled: false
status:
fieldName: status
publicName: status
enhancer:
id: ''
disabled: false
dependencies:
fieldName: dependencies
publicName: dependencies
enhancer:
id: ''
disabled: false
third_party_settings:
fieldName: third_party_settings
publicName: third_party_settings
enhancer:
id: ''
disabled: false
_core:
fieldName: _core
publicName: _core
enhancer:
id: ''
disabled: false
id:
fieldName: id
publicName: id
enhancer:
id: ''
disabled: false
label:
fieldName: label
publicName: label
enhancer:
id: ''
disabled: false
module:
fieldName: module
publicName: module
enhancer:
id: ''
disabled: false
description:
fieldName: description
publicName: description
enhancer:
id: ''
disabled: false
tag:
fieldName: tag
publicName: tag
enhancer:
id: ''
disabled: false
base_table:
fieldName: base_table
publicName: base_table
enhancer:
id: ''
disabled: false
base_field:
fieldName: base_field
publicName: base_field
enhancer:
id: ''
disabled: false
display:
fieldName: display
publicName: display
enhancer:
id: ''
disabled: false
@@ -0,0 +1,31 @@
<?php
/**
* @file
* Hooks provided by farm_api.
*
* This file contains no working PHP code; it exists to provide additional
* documentation for doxygen as well as to document hooks in the standard
* Drupal manner.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Alter the a "meta.farm" data in the root /api endpoint.
*
* @param array &$data
* The data to be altered.
*/
function hook_farm_api_meta_alter(array &$data) {
// Add a custom key.
$data['mykey'] = 'myvalue';
}
/**
* @} End of "addtogroup hooks".
*/
@@ -0,0 +1,13 @@
name: farmOS API
description: Provides configuration for the farmOS API.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- drupal:jsonapi
- entity:entity
- jsonapi_extras:jsonapi_extras
- jsonapi_schema:jsonapi_schema
- simple_oauth:simple_oauth
- simple_oauth:simple_oauth_static_scope
- subrequests:subrequests
@@ -0,0 +1,147 @@
<?php
/**
* @file
* Install, update and uninstall functions for the farm_api module.
*/
use Drupal\Core\Utility\Error;
/**
* Implements hook_install().
*/
function farm_api_install() {
// Allow JSON:API write operations.
\Drupal::configFactory()->getEditable('jsonapi.settings')->set('read_only', FALSE)->save();
// Change the base JSON:API path to /api.
\Drupal::configFactory()->getEditable('jsonapi_extras.settings')->set('path_prefix', 'api')->save();
// Load the simple_oauth module settings.
$simple_oauth_settings = \Drupal::configFactory()->getEditable('simple_oauth.settings');
// Explicitly set the public/private key path.
$simple_oauth_settings->set('public_key', '../keys/public.key');
$simple_oauth_settings->set('private_key', '../keys/private.key');
// Use static scopes by default.
$simple_oauth_settings->set('scope_provider', 'static');
// Save simple_oauth settings.
$simple_oauth_settings->save();
// Generate key files for simple_oauth module.
// Code adapted from the contenta_jsonapi profile install tasks:
// https://github.com/contentacms/contenta_jsonapi/blob/8.x-3.x/contenta_jsonapi.profile
// Build all the dependencies manually to avoid having to rely on the
// container to be ready.
$dir_name = 'keys';
/** @var \Drupal\simple_oauth\Service\KeyGeneratorService $key_gen */
$key_gen = \Drupal::service('simple_oauth.key.generator');
/** @var \Drupal\simple_oauth\Service\Filesystem\FileSystemChecker $file_system_checker */
$file_system_checker = \Drupal::service('simple_oauth.filesystem_checker');
/** @var \Drupal\Core\File\FileSystem $file_system */
$file_system = \Drupal::service('file_system');
// Save keys in the "keys" directory outside of the webroot.
$relative_path = DRUPAL_ROOT . '/../' . $dir_name;
if (!$file_system_checker->isDirectory($relative_path)) {
$file_system->mkdir($relative_path);
}
$keys_path = $file_system->realpath($relative_path);
$pub_filename = sprintf('%s/public.key', $keys_path);
$pri_filename = sprintf('%s/private.key', $keys_path);
// Attempt to create keys if they don't exist.
if (!$file_system_checker->fileExist($pub_filename) || !$file_system_checker->fileExist($pri_filename)) {
try {
$key_gen->generateKeys($keys_path);
}
catch (\Exception $e) {
$logger = \Drupal::logger('farm_api');
Error::logException($logger, $e);
}
}
// Delete the "Default Consumer" created by the consumers module.
$default_consumer = \Drupal::entityTypeManager()->getStorage('consumer')
->loadByProperties(['label' => 'Default Consumer']);
if (!empty($default_consumer)) {
$default_consumer = reset($default_consumer);
$default_consumer->delete();
}
}
/**
* Implements hook_update_dependencies().
*/
function farm_api_update_dependencies() {
// The Consumers module added a client_id base field in version 1.14, which
// replaces our custom client_id field. We need to migrate the client IDs
// from our old field to the new field, which requires running our own
// update hooks before and after those of the Consumers module.
$dependencies['consumers'][8108] = [
'farm_api' => 9000,
];
$dependencies['farm_api'][9001] = [
'consumers' => 8109,
];
return $dependencies;
}
/**
* Save client_id values and uninstall farmOS client_id field.
*/
function farm_api_update_9000(&$sandbox) {
// This update hook must run before consumers_update_8108().
// @see farm_api_update_dependencies().
// Get all client_id values from the database.
$client_ids = [];
$result = \Drupal::database()->query('SELECT entity_id, client_id_value FROM {consumer__client_id}')->fetchAll();
foreach ($result as $record) {
$client_ids[$record->entity_id] = $record->client_id_value;
}
// Save the client_id values to Drupal state.
if (!empty($client_ids)) {
\Drupal::state()->set('farm_api_consumer_client_ids', $client_ids);
}
// Uninstall the client_id field.
/** @var \Drupal\entity\BundleFieldDefinition $definition */
$definition = \Drupal::service('farm_field.factory')->bundleFieldDefinition(['type' => 'string']);
$definition->setTargetEntityTypeId('consumer');
$definition->setName('client_id');
\Drupal::entityDefinitionUpdateManager()->uninstallFieldStorageDefinition($definition);
}
/**
* Restore client_id values saved from farmOS client_id field.
*/
function farm_api_update_9001(&$sandbox) {
// This update hook must run after consumers_update_8109().
// @see farm_api_update_dependencies().
// Load saved client_id values from old client_id field.
$client_ids = \Drupal::state()->get('farm_api_consumer_client_ids', []);
if (empty($client_ids)) {
return;
}
// Save client_id values to new client_id field.
// Use SQL update instead of entity save so tokens do not become invalidated.
$database = \Drupal::database();
foreach ($client_ids as $consumer_id => $client_id) {
$database->update('consumer_field_data')
->fields(['client_id' => $client_id])
->condition('id', $consumer_id)
->execute();
}
}
@@ -0,0 +1,4 @@
farm_api:
default_permissions:
- grant simple_oauth codes
- issue subrequests
@@ -0,0 +1,53 @@
<?php
/**
* @file
* Contains farm_api.module.
*/
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\entity\BundleFieldDefinition;
/**
* Implements hook_consumers_list_alter().
*
* Display the client_id in the list of consumers.
*/
function farm_api_consumers_list_alter(&$data, $context) {
if ($context['type'] === 'header') {
$data['client_id'] = t('Client ID');
}
elseif ($context['type'] === 'row') {
$entity = $context['entity'];
$data['client_id'] = NULL;
if ($client_id = $entity->get('client_id')->value) {
$data['client_id'] = $client_id;
}
}
}
/**
* Implements hook_entity_base_field_info().
*/
function farm_api_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
// Add allowed_origins field to the consumer entity.
if ($entity_type->id() == 'consumer') {
$fields['allowed_origins'] = BundleFieldDefinition::create('string')
->setLabel(t('Allowed origins'))
->setDescription(t('Configure CORS origins for this consumer.'))
->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
->setDisplayOptions('form', [
'type' => 'string_textfield',
'settings' => [
'size' => 255,
'placeholder' => 'https://example.com',
],
]);
}
return $fields;
}
@@ -0,0 +1,64 @@
<?php
/**
* @file
* Post update functions for farm_settings module.
*/
/**
* Remove farm_api consumer bundle fields.
*/
function farm_api_post_update_remove_consumer_fields(&$sandbox = NULL) {
// Remove old consumer fields.
$fields = [
'grant_user_access',
'limit_user_access',
'limit_requested_access',
];
foreach ($fields as $field) {
$entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$roles_field_definition = $entity_definition_update_manager->getFieldStorageDefinition($field, 'consumer');
$entity_definition_update_manager->uninstallFieldStorageDefinition($roles_field_definition);
}
}
/**
* Enable static oauth2 scopes.
*/
function farm_api_post_update_enable_static_oauth2_scopes(&$sandbox = NULL) {
// Enable static scope module.
if (!\Drupal::service('module_handler')->moduleExists('simple_oauth_static_scope')) {
\Drupal::service('module_installer')->install(['simple_oauth_static_scope']);
}
// Use static scope provider.
$simple_oauth_settings = \Drupal::configFactory()->getEditable('simple_oauth.settings');
$simple_oauth_settings->set('scope_provider', 'static');
$simple_oauth_settings->save();
}
/**
* Enable default consumer module.
*/
function farm_api_post_update_enable_default_consumer_module(&$sandbox = NULL) {
// Check for an existing farm default consumer.
$consumers = \Drupal::entityTypeManager()->getStorage('consumer')
->loadByProperties(['client_id' => 'farm']);
if (!empty($consumers)) {
// Enable default consumer module.
if (!\Drupal::service('module_handler')->moduleExists('farm_api_default_consumer')) {
\Drupal::service('module_installer')->install(['farm_api_default_consumer']);
}
// Update values on the consumer.
/** @var \Drupal\consumers\Entity\ConsumerInterface $farm_default */
$farm_default = reset($consumers);
$farm_default->set('grant_types', ['authorization_code', 'refresh_token', 'password']);
$farm_default->save();
}
}
@@ -0,0 +1,12 @@
services:
# Add CORS headers for allowed origins configured on consumers.
farm_api.cors_event_subscriber:
class: Drupal\farm_api\EventSubscriber\CorsResponseEventSubscriber
arguments: ['@entity_type.manager']
tags:
- { name: event_subscriber }
# Alter the root /api endpoint to include a meta.farm object.
farm_api.route_subscriber:
class: Drupal\farm_api\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
@@ -0,0 +1,8 @@
name: farmOS Default API Consumer
description: Provides a default consumer for using the farmOS API.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- farm:farm_api
- simple_oauth_password_grant:simple_oauth_password_grant
@@ -0,0 +1,56 @@
<?php
/**
* @file
* Install and uninstall functions for the farm_api_default_consumer module.
*/
use Drupal\consumers\Entity\Consumer;
/**
* Implements hook_install().
*/
function farm_api_default_consumer_install() {
// Check for an existing farm default consumer.
$consumers = \Drupal::entityTypeManager()->getStorage('consumer')
->loadByProperties(['client_id' => 'farm']);
// If not found, create the farm default consumer.
if (empty($consumers)) {
$base_url = \Drupal::service('router.request_context')->getCompleteBaseUrl();
$farm_consumer = Consumer::create([
'label' => 'Farm default',
'client_id' => 'farm',
'access_token_expiration' => 3600,
'grant_types' => [
'authorization_code',
'refresh_token',
'password',
],
'redirect' => $base_url,
'is_default' => TRUE,
'secret' => NULL,
'confidential' => FALSE,
'third_party' => FALSE,
]);
$farm_consumer->save();
}
}
/**
* Implements hook_uninstall().
*/
function farm_api_default_consumer_uninstall() {
// Load the default farm consumer.
$consumers = \Drupal::entityTypeManager()->getStorage('consumer')
->loadByProperties(['client_id' => 'farm']);
// If found, delete the consumer.
if (!empty($consumers)) {
$farm_consumer = reset($consumers);
$farm_consumer->delete();
}
}
@@ -0,0 +1,108 @@
<?php
namespace Drupal\farm_api\Controller;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ProfileExtensionList;
use Drupal\Core\Session\AccountInterface;
use Drupal\jsonapi\CacheableResourceResponse;
use Drupal\jsonapi\Controller\EntryPoint;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\JsonApiResource\NullIncludedData;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Extend the core jsonapi EntryPoint controller.
*
* Adds a "meta.farm" key to root /api endpoint.
*
* @ingroup farm
*
* @phpstan-ignore-next-line
*/
class FarmEntryPoint extends EntryPoint {
/**
* Farm profile info.
*
* @var mixed[]
*/
protected $farmProfileInfo;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* EntryPoint constructor.
*
* @param \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface $resource_type_repository
* The resource type repository.
* @param \Drupal\Core\Session\AccountInterface $user
* The current user.
* @param \Drupal\Core\Extension\ProfileExtensionList $profile_extension_list
* The profile extension list service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(ResourceTypeRepositoryInterface $resource_type_repository, AccountInterface $user, ProfileExtensionList $profile_extension_list, ModuleHandlerInterface $module_handler) {
parent::__construct($resource_type_repository, $user);
$this->farmProfileInfo = $profile_extension_list->getExtensionInfo('farm');
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('jsonapi.resource_type.repository'),
$container->get('current_user'),
$container->get('extension.list.profile'),
$container->get('module_handler'),
);
}
/**
* {@inheritdoc}
*/
public function index() {
// Get the base url.
global $base_url;
// Get normal response cache and data.
/** @var \Drupal\jsonapi\CacheableResourceResponse $response */
$response = parent::index();
$cacheability = $response->getCacheableMetadata();
$data = $response->getResponseData();
// Get urls and meta.
$urls = $data->getLinks();
$meta = $data->getMeta();
// Add a "farm" object to meta.
$meta['farm'] = [
'name' => $this->config('system.site')->get('name'),
'url' => $base_url,
'version' => $this->farmProfileInfo['version'],
];
// Allow modules to add additional meta information.
$this->moduleHandler->alter('farm_api_meta', $meta['farm']);
// Build a new response.
$new_response = new CacheableResourceResponse(new JsonApiDocumentTopLevel(new ResourceObjectData([]), new NullIncludedData(), $urls, $meta));
// Add the original response's cacheability.
$new_response->addCacheableDependency($cacheability);
return $new_response;
}
}
@@ -0,0 +1,83 @@
<?php
namespace Drupal\farm_api\EventSubscriber;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Responds to the Kernel Response event to add CORS headers.
*
* CORS headers are only added to requests from the allowed origins configured
* on consumer entities.
*/
class CorsResponseEventSubscriber implements EventSubscriberInterface {
/**
* Entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new CorsResponseEventSubscriber.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['addCorsHeaders'];
return $events;
}
/**
* Adds CORS headers to the response.
*
* @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
* The response event.
*/
public function addCorsHeaders(ResponseEvent $event) {
// Get the request headers.
$request = $event->getRequest();
$request_headers = $request->headers->all();
// Bail if the request has no origin header.
if (empty($request_headers['origin'])) {
return;
}
$request_origin = reset($request_headers['origin']);
// Load allowed_origins from all consumer entities.
$consumers = $this->entityTypeManager->getStorage('consumer')->loadMultiple();
$allowed_origins = array_reduce($consumers, function ($carry, $consumer) {
/** @var \Drupal\Core\Field\FieldItemListInterface $list */
$list = $consumer->get('allowed_origins');
$list_values = array_map(function ($list_item) {
return $list_item['value'] ? trim($list_item['value']) : NULL;
}, $list->getValue());
return array_merge($carry, $list_values);
}, []);
// Set the response headers if the request origin is allowed.
if (in_array($request_origin, $allowed_origins)) {
$response = $event->getResponse();
$response->headers->set('Access-Control-Allow-Origin', $request_origin, TRUE);
$response->headers->set('Access-Control-Allow-Credentials', 'true', TRUE);
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type,Content-Disposition,Authorization,X-CSRF-Token', TRUE);
$response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,HEAD,OPTIONS', TRUE);
$response->headers->set('Vary', 'Origin', TRUE);
}
}
}
@@ -0,0 +1,28 @@
<?php
namespace Drupal\farm_api\Routing;
use Drupal\Core\Routing\RouteObjectInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\farm_api\Controller\FarmEntryPoint;
use Symfony\Component\Routing\RouteCollection;
/**
* Alter routes for the farm_api module.
*
* @ingroup farm
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
// Alter the root jsonapi.resource_list route to use the FarmEntryPoint
// controller. This allows us to add the meta.farm object.
if ($route = $collection->get('jsonapi.resource_list')) {
$route->setDefaults([RouteObjectInterface::CONTROLLER_NAME => FarmEntryPoint::class . '::index']);
}
}
}
@@ -0,0 +1,7 @@
langcode: en
status: true
id: test
label: Test
description: ''
workflow: asset_default
new_revision: true
@@ -0,0 +1,8 @@
langcode: en
status: true
id: test
label: Test
description: ''
name_pattern: 'Test log [log:id]'
workflow: log_default
new_revision: true
@@ -0,0 +1,9 @@
name: farmOS API Tests
description: 'Support module for farmOS API testing.'
type: module
package: Testing
core_version_requirement: ^10
dependencies:
- farm:asset
- log:log
- simple_oauth_password_grant:simple_oauth_password_grant
@@ -0,0 +1,12 @@
test:password:
description: 'Static scope for password grant.'
umbrella: false
grant_types:
authorization_code:
status: true
description: 'Authorization code grant.'
password:
status: true
description: 'Password grant'
granularity: 'permission'
permission: 'access content'
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_api_test\Plugin\Asset\AssetType;
use Drupal\farm_entity\Plugin\Asset\AssetType\FarmAssetType;
/**
* Provides the test asset type.
*
* @AssetType(
* id = "test",
* label = @Translation("Test"),
* )
*/
class Test extends FarmAssetType {
}
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_api_test\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the test log type.
*
* @LogType(
* id = "test",
* label = @Translation("Test"),
* )
*/
class Test extends FarmLogType {
}
@@ -0,0 +1,128 @@
<?php
namespace Drupal\Tests\farm_api\Functional;
use Drupal\Core\Url;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
use Drupal\Tests\jsonapi\Functional\JsonApiRequestTestTrait;
use Drupal\consumers\Entity\Consumer;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\ResponseInterface;
/**
* Tests that CORS headers are properly added.
*
* @group farm
*/
class CorsResponseEventSubscriberTest extends FarmBrowserTestBase {
use JsonApiRequestTestTrait;
/**
* Test consumer entity.
*
* @var \Drupal\consumers\Entity\Consumer
*/
protected $consumer;
/**
* {@inheritdoc}
*/
protected static $modules = [
'farm_api',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create a consumer for testing.
$this->consumer = Consumer::create([
'label' => $this->getRandomGenerator()->name(),
]);
$this->consumer->save();
}
/**
* Test CORS response headers are correctly added.
*/
public function testCorsResponseHeaders() {
// A request with no Origin should not have CORS headers on the response.
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$uri = "base://api";
$response = $this->request('OPTIONS', Url::fromUri($uri), $request_options);
$this->assertSame(200, $response->getStatusCode());
$this->assertValidCorsHeaders($response);
// Try an invalid origin.
$farmos_app_origin = 'https://farmOS.app';
$request_options[RequestOptions::HEADERS]['Origin'] = $farmos_app_origin;
$response = $this->request('OPTIONS', Url::fromUri($uri), $request_options);
$this->assertSame(200, $response->getStatusCode());
$this->assertValidCorsHeaders($response);
// Configure an allowed origin on the consumer.
$this->consumer->set('allowed_origins', [$farmos_app_origin]);
$this->consumer->save();
// Make a request with the allowed origin configured.
$response = $this->request('OPTIONS', Url::fromUri($uri), $request_options);
$this->assertSame(200, $response->getStatusCode());
$this->assertValidCorsHeaders($response, $farmos_app_origin);
// Add another allowed_origin and test that multiple allowed origins work.
$custom_app_origin = 'https://customApp.com';
$this->consumer->set('allowed_origins', [$farmos_app_origin, $custom_app_origin]);
$this->consumer->save();
// Make a request from the first allowed origin.
$request_options[RequestOptions::HEADERS]['Origin'] = $farmos_app_origin;
$response = $this->request('OPTIONS', Url::fromUri($uri), $request_options);
$this->assertSame(200, $response->getStatusCode());
$this->assertValidCorsHeaders($response, $farmos_app_origin);
// Make a request from the second allowed origin.
$request_options[RequestOptions::HEADERS]['Origin'] = $custom_app_origin;
$response = $this->request('OPTIONS', Url::fromUri($uri), $request_options);
$this->assertSame(200, $response->getStatusCode());
$this->assertValidCorsHeaders($response, $custom_app_origin);
}
/**
* Helper method to test valid CORS headers.
*
* @param \Psr\Http\Message\ResponseInterface $response
* The response to check.
* @param string|null $origin
* An optional origin to check. If NULL, then the request should have no
* CORS headers.
*/
protected function assertValidCorsHeaders(ResponseInterface $response, ?string $origin = NULL) {
// Cors headers to test.
$cors_headers = [
'Access-Control-Allow-Origin' => $origin,
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Headers' => 'Content-Type,Content-Disposition,Authorization,X-CSRF-Token',
'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,HEAD,OPTIONS',
];
// Check if the response should contain headers.
$needs_cors = !empty($origin);
foreach ($cors_headers as $header => $value) {
$this->assertEquals($needs_cors, $response->hasHeader($header), 'Response has correct CORS headers.');
if ($needs_cors) {
$this->assertEquals($value, $response->getHeader($header)[0], 'Response has correct header value.');
}
}
// Confirm that the "Vary" header contains "Origin" when CORS is in use.
if ($needs_cors) {
$this->assertTrue(str_contains($response->getHeader('Vary')[0], 'Origin'), 'Response Vary header contains Origin.');
}
}
}
@@ -0,0 +1,112 @@
<?php
namespace Drupal\Tests\farm_api\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Url;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
use Drupal\Tests\jsonapi\Functional\JsonApiRequestTestTrait;
use GuzzleHttp\RequestOptions;
/**
* Tests the API entry point functionality.
*
* @group farm
*/
class EntryPointTest extends FarmBrowserTestBase {
use JsonApiRequestTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'basic_auth',
'node',
'farm_api',
'views',
];
/**
* Run all tests.
*/
public function testAll() {
$this->doTestEntryPoint();
$this->doTestFarmMeta();
}
/**
* Test GET to the entry point.
*
* We extend the core JSONAPI EntryPoint controller to include a 'meta' key
* in the root controller. We need to test that we aren't changing anything
* else.
*
* This test is a copy of the core JSONAPI testEntryPoint test with the
* following modifications:
* - The base path is /api, not /jsonapi
* - The root document MUST have a 'meta' key.
*
* @see \Drupal\Tests\jsonapi\Functional\EntryPointTest
*/
public function doTestEntryPoint() {
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$response = $this->request('GET', Url::fromUri('base://api'), $request_options);
$document = Json::decode((string) $response->getBody());
$expected_cache_contexts = [
'url.query_args',
'url.site',
'user.roles:authenticated',
];
$this->assertTrue($response->hasHeader('X-Drupal-Cache-Contexts'));
$optimized_expected_cache_contexts = \Drupal::service('cache_contexts_manager')->optimizeTokens($expected_cache_contexts);
$this->assertSame($optimized_expected_cache_contexts, explode(' ', $response->getHeader('X-Drupal-Cache-Contexts')[0]));
$links = $document['links'];
$this->assertMatchesRegularExpression('/.*\/api/', $links['self']['href']);
$this->assertMatchesRegularExpression('/.*\/api\/user\/user/', $links['user--user']['href']);
$this->assertMatchesRegularExpression('/.*\/api\/node_type\/node_type/', $links['node_type--node_type']['href']);
// farm_api alters the root document to include a 'meta' key.
$this->assertArrayHasKey('meta', $document);
// A `me` link must be present for authenticated users.
$user = $this->createUser();
$request_options[RequestOptions::HEADERS]['Authorization'] = 'Basic ' . base64_encode($user->name->value . ':' . $user->passRaw);
$response = $this->request('GET', Url::fromUri('base://api'), $request_options);
$document = Json::decode((string) $response->getBody());
$this->assertArrayHasKey('meta', $document);
$this->assertStringEndsWith('/api/user/user/' . $user->uuid(), $document['meta']['links']['me']['href']);
}
/**
* Test that the meta.farm data is correct.
*/
public function doTestFarmMeta() {
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$response = $this->request('GET', Url::fromUri('base://api'), $request_options);
$document = Json::decode((string) $response->getBody());
// Assert that the meta key exists.
$this->assertArrayHasKey('meta', $document);
// Assert that the meta.farm key exists.
$this->assertArrayHasKey('farm', $document['meta']);
// Get the farm profile info.
$farm_info = \Drupal::service('extension.list.profile')->getExtensionInfo('farm');
// Array of expected values.
$expected_values = [
'name' => $this->config('system.site')->get('name'),
'url' => $this->baseUrl,
'version' => $farm_info['version'],
];
foreach ($expected_values as $key => $value) {
$this->assertArrayHasKey($key, $document['meta']['farm']);
$this->assertEquals($value, $document['meta']['farm'][$key]);
}
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\Tests\farm_api\Functional;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
/**
* Tests hook_install functionality of farm_api module.
*
* This must be implemented as a BrowserTest so that the module is fully
* installed while testing. The KernelTestBase does not fully install modules.
*
* @group farm
*/
class InstallTest extends FarmBrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'simple_oauth',
'farm_api',
// @todo Investigate why Views is needed.
'views',
];
/**
* Tests keys were created.
*/
public function testKeys() {
// Key directory.
$dir_name = 'keys';
// Save keys in the "keys" directory outside of the webroot.
$relative_path = DRUPAL_ROOT . '/../' . $dir_name;
$this->assertDirectoryExists($relative_path);
$pub_filename = sprintf('%s/public.key', $relative_path);
$pri_filename = sprintf('%s/private.key', $relative_path);
$this->assertFileExists($pub_filename);
$this->assertFileExists($pri_filename);
}
}
@@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\farm_api\Functional;
use Drupal\Tests\simple_oauth\Functional\TokenBearerFunctionalTestBase;
/**
* Base class that handles common logic for OAuth tests.
*
* @group farm
*/
class OauthTestBase extends TokenBearerFunctionalTestBase {
/**
* {@inheritdoc}
*/
protected $profile = 'farm';
/**
* {@inheritdoc}
*/
protected static $modules = [
'image',
'node',
'serialization',
'simple_oauth',
'text',
'user',
'farm_api',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Add a client_id to the client.
$this->client->set('client_id', 'farm_test');
$this->client->set('confidential', FALSE);
$this->client->save();
}
}
@@ -0,0 +1,223 @@
<?php
namespace Drupal\Tests\farm_api\Kernel;
use Drupal\Component\Serialization\Json;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Tests farmOS API features.
*
* @group farm
*/
class FarmApiTest extends KernelTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
protected $profile = 'farm';
/**
* {@inheritdoc}
*/
protected static $modules = [
'asset',
'consumers',
'entity',
'farm_api',
'farm_api_test',
'farm_entity',
'farm_entity_views',
'farm_field',
'farm_log_asset',
'farm_role',
'farm_role_roles',
'file',
'image',
'jsonapi',
'jsonapi_extras',
'log',
'options',
'serialization',
'simple_oauth',
'state_machine',
'system',
'user',
'views',
];
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
$this->installEntitySchema('consumer');
$this->installEntitySchema('asset');
$this->installEntitySchema('log');
$this->installConfig([
'farm_api_test',
'farm_entity_views',
'farm_role_roles',
'jsonapi',
'jsonapi_extras',
'system',
]);
// Set the install profile.
// This is necessary because farm_api's FarmEntryPoint needs to load the
// farm profile information from Drupal's extension list service. During
// kernel tests the installProfile property of the ExtensionList class does
// not get set automatically.
$this->setInstallProfile('farm');
// Set the site name so that we can check for it in /api meta.farm info.
\Drupal::configFactory()->getEditable('system.site')->set('name', 'API Test')->save();
// Allow JSON:API write operations and change the base path to /api.
// These would normally be done by farm_api_install(), which does not run
// in Kernel tests (it also does other things we don't need).
\Drupal::configFactory()->getEditable('jsonapi.settings')->set('read_only', FALSE)->save();
\Drupal::configFactory()->getEditable('jsonapi_extras.settings')->set('path_prefix', 'api')->save();
// Set up a user with the farm_manager role.
$user = $this->setUpCurrentUser([], [], FALSE);
$user->addRole('farm_manager');
}
/**
* Test common farmOS API requests.
*/
public function testApi() {
// Test that the API root path is /api and it contains meta.farm info.
$data = $this->apiRequest('/api');
$this->assertNotEmpty($data['meta']['farm']);
$this->assertEquals('API Test', $data['meta']['farm']['name']);
// Test creating an asset.
$asset_type = 'asset--test';
$payload = [
'type' => $asset_type,
'attributes' => [
'name' => 'Test asset',
],
];
$data = $this->apiRequest('/api/asset/test', 'POST', $payload);
$this->assertNotEmpty($data['data']['id']);
$this->assertEquals($asset_type, $data['data']['type']);
$this->assertEquals($payload['attributes']['name'], $data['data']['attributes']['name']);
// Get the asset ID.
$asset_id = $data['data']['id'];
// Test creating a log that references the asset.
$log_type = 'log--test';
$payload = [
'type' => $log_type,
'relationships' => [
'asset' => [
'data' => [
[
'id' => $asset_id,
'type' => $asset_type,
],
],
],
],
];
$data = $this->apiRequest('/api/log/test', 'POST', $payload);
$this->assertNotEmpty($data['data']['id']);
$this->assertEquals($log_type, $data['data']['type']);
$this->assertEquals($asset_id, $data['data']['relationships']['asset']['data'][0]['id']);
// Get the log ID.
$log_id = $data['data']['id'];
// Test that the asset and log appear in collection endpoints.
$data = $this->apiRequest('/api/asset/test');
$this->assertCount(1, $data['data']);
$this->assertEquals($asset_id, $data['data'][0]['id']);
$data = $this->apiRequest('/api/log/test');
$this->assertCount(1, $data['data']);
$this->assertEquals($log_id, $data['data'][0]['id']);
// Test retrieving both asset and log individually by UUID.
$data = $this->apiRequest('/api/asset/test/' . $asset_id);
$this->assertEquals($asset_id, $data['data']['id']);
$data = $this->apiRequest('/api/log/test/' . $log_id);
$this->assertEquals($log_id, $data['data']['id']);
// Test updating assets and logs.
$payload = [
'type' => $asset_type,
'id' => $asset_id,
'attributes' => [
'name' => 'Updated asset name',
],
];
$data = $this->apiRequest('/api/asset/test/' . $asset_id, 'PATCH', $payload);
$this->assertEquals($asset_id, $data['data']['id']);
$data = $this->apiRequest('/api/asset/test/' . $asset_id);
$this->assertEquals($payload['attributes']['name'], $data['data']['attributes']['name']);
$payload = [
'type' => $log_type,
'id' => $log_id,
'attributes' => [
'name' => 'Updated log name',
],
];
$data = $this->apiRequest('/api/log/test/' . $log_id, 'PATCH', $payload);
$this->assertEquals($log_id, $data['data']['id']);
$data = $this->apiRequest('/api/log/test/' . $log_id);
$this->assertEquals($payload['attributes']['name'], $data['data']['attributes']['name']);
// Test deleting logs and assets.
$this->apiRequest('/api/log/test/' . $log_id, 'DELETE');
$data = $this->apiRequest('/api/log/test');
$this->assertCount(0, $data['data']);
$data = $this->apiRequest('/api/asset/test/' . $asset_id, 'DELETE');
$data = $this->apiRequest('/api/asset/test');
$this->assertCount(0, $data['data']);
}
/**
* Helper function for performing an API request.
*
* @param string $endpoint
* The API endpoint.
* @param string $method
* The request method (eg: GET, POST, PATCH, DELETE).
* @param array $payload
* Array of data to send as a payload.
*
* @return array
* An array of JSON-decoded data returned by the request.
*/
protected function apiRequest(string $endpoint, string $method = 'GET', array $payload = []) {
$http_kernel = $this->container->get('http_kernel');
$content = '';
if (!empty($payload)) {
$content = Json::encode([
'data' => $payload,
]);
}
$request = Request::create($endpoint, $method, [], [], [], [], $content);
$request->headers->set('Accept', 'application/vnd.api+json');
$request->headers->set('Content-Type', 'application/vnd.api+json');
$response = $http_kernel->handle($request);
$expected_response = [
'GET' => Response::HTTP_OK,
'POST' => Response::HTTP_CREATED,
'PATCH' => Response::HTTP_OK,
'DELETE' => Response::HTTP_NO_CONTENT,
];
$this->assertEquals($expected_response[$method], $response->getStatusCode());
return Json::decode($response->getContent());
}
}
@@ -0,0 +1,11 @@
name: Asset
description: Provides an asset entity type for real world record keeping.
type: module
package: Asset
core_version_requirement: ^10
dependencies:
- drupal:system (>=8.8.0)
- drupal:user
- drupal:views
- entity:entity
- state_machine:state_machine
@@ -0,0 +1,11 @@
entity.asset.add_page:
route_name: 'entity.asset.add_page'
title: 'Add asset'
appears_on:
- entity.asset.collection
entity.asset_type.add_form:
route_name: 'entity.asset_type.add_form'
title: 'Add asset type'
appears_on:
- entity.asset_type.collection
@@ -0,0 +1,5 @@
entity.asset_type.collection:
title: 'Asset types'
route_name: entity.asset_type.collection
description: 'List of asset types'
parent: system.admin_structure
@@ -0,0 +1,4 @@
entity.asset.collection:
route_name: entity.asset.collection
title: 'Assets'
base_route: system.admin_content
@@ -0,0 +1,123 @@
<?php
/**
* @file
* Hooks and customizations for the asset module.
*/
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\asset\Entity\AssetInterface;
use Drupal\asset\Event\AssetEvent;
/**
* Implements hook_help().
*/
function asset_help($route_name, RouteMatchInterface $route_match) {
$output = '';
// Main module help for the asset module.
if ($route_name == 'help.page.asset') {
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Provides asset entity') . '</p>';
}
return $output;
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function asset_asset_presave(AssetInterface $asset) {
// Dispatch an event on asset presave.
// @todo Replace this with core event via https://www.drupal.org/node/2551893.
$event = new AssetEvent($asset);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, AssetEvent::PRESAVE);
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function asset_asset_insert(AssetInterface $asset) {
// Dispatch an event on asset insert.
// @todo Replace this with core event via https://www.drupal.org/node/2551893.
$event = new AssetEvent($asset);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, AssetEvent::INSERT);
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function asset_asset_update(AssetInterface $asset) {
// Dispatch an event on asset update.
// @todo Replace this with core event via https://www.drupal.org/node/2551893.
$event = new AssetEvent($asset);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, AssetEvent::UPDATE);
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function asset_asset_delete(AssetInterface $asset) {
// Dispatch an event on asset delete.
// @todo Replace this with core event via https://www.drupal.org/node/2551893.
$event = new AssetEvent($asset);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, AssetEvent::DELETE);
}
/**
* Implements hook_theme().
*/
function asset_theme() {
return [
'asset' => [
'render element' => 'elements',
],
];
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function asset_theme_suggestions_asset(array $variables) {
$suggestions = [];
$asset = $variables['elements']['#asset'];
$sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
$suggestions[] = 'asset__' . $sanitized_view_mode;
$suggestions[] = 'asset__' . $asset->bundle();
$suggestions[] = 'asset__' . $asset->bundle() . '__' . $sanitized_view_mode;
$suggestions[] = 'asset__' . $asset->id();
$suggestions[] = 'asset__' . $asset->id() . '__' . $sanitized_view_mode;
return $suggestions;
}
/**
* Prepares variables for asset templates.
*
* Default template: asset.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the asset information and any
* fields attached to the asset. Properties used:
* - #asset: A \Drupal\asset\Entity\Asset object. The asset entity.
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_asset(array &$variables) {
$variables['asset'] = $variables['elements']['#asset'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
@@ -0,0 +1,19 @@
administer assets:
title: 'Administer assets'
description: 'Admin access to all asset entities.'
restrict access: true
administer asset types:
title: 'Administer asset types'
description: 'Maintain the types of content available and the fields that are associated with those types.'
restrict access: true
view all asset revisions:
title: 'View all asset revisions'
description: 'Allow viewing asset entity revisions.'
restrict access: true
revert all asset revisions:
title: 'Revert all asset revisions'
description: 'Allow reverting to a previous asset entity revision.'
restrict access: true
@@ -0,0 +1,3 @@
asset:
label: asset
entity_type: asset
@@ -0,0 +1,18 @@
asset_default:
id: asset_default
group: asset
label: 'Default'
states:
active:
label: Active
archived:
label: Archived
transitions:
archive:
label: 'Archive'
from: [active]
to: archived
to_active:
label: 'Make active'
from: [archived]
to: active
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- asset
id: asset_activate_action
label: 'Unarchive asset'
type: asset
plugin: 'asset_activate_action'
configuration: { }
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- asset
id: asset_archive_action
label: 'Archive asset'
type: asset
plugin: 'asset_archive_action'
configuration: { }
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- asset
id: asset_clone_action
label: 'Clone asset'
type: asset
plugin: 'asset_clone_action'
configuration: { }
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- asset
id: asset_delete_action
label: 'Delete asset'
type: asset
plugin: entity:delete_action:asset
configuration: { }
@@ -0,0 +1,730 @@
langcode: en
status: true
dependencies:
module:
- asset
- options
- user
id: asset_admin
label: 'Asset admin'
module: views
description: 'Find and manage asset entities.'
tag: default
base_table: asset_field_data
base_field: id
display:
default:
id: default
display_title: Master
display_plugin: default
position: 0
display_options:
title: Assets
fields:
asset_bulk_form:
id: asset_bulk_form
table: asset
field: asset_bulk_form
relationship: none
group_type: group
admin_label: ''
entity_type: asset
plugin_id: bulk_form
label: 'Bulk update'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
action_title: 'With selection'
include_exclude: exclude
selected_actions: { }
status:
id: status
table: asset_field_data
field: status
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: status
plugin_id: field
label: Status
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: list_default
settings: { }
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
id:
id: id
table: asset_field_data
field: id
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: id
plugin_id: field
label: ID
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: number_integer
settings:
thousand_separator: ''
prefix_suffix: true
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
name:
id: name
table: asset_field_data
field: name
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: name
plugin_id: field
label: Name
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: string
settings:
link_to_entity: true
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
type:
id: type
table: asset_field_data
field: type
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: type
plugin_id: field
label: 'Asset type'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: target_id
type: entity_reference_label
settings:
link: true
group_column: target_id
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
uid:
id: uid
table: asset_field_data
field: uid
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: uid
plugin_id: field
label: 'Authored by'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: target_id
type: entity_reference_label
settings:
link: true
group_column: target_id
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
operations:
id: operations
table: asset
field: operations
relationship: none
group_type: group
admin_label: ''
entity_type: null
entity_field: null
plugin_id: entity_operations
label: 'Operations links'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: 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_empty: false
empty_zero: false
hide_alter_empty: true
destination: true
pager:
type: full
options:
offset: 0
items_per_page: 25
total_pages: null
id: 0
tags:
next: 'Next ›'
previous: '‹ Previous'
first: '« First'
last: 'Last »'
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
quantity: 9
pagination_heading_level: h4
exposed_form:
type: basic
options:
submit_button: Filter
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
access:
type: perm
options:
perm: 'administer assets'
cache:
type: tag
options: { }
empty:
area_text_custom:
id: area_text_custom
table: views
field: area_text_custom
relationship: none
group_type: group
admin_label: ''
plugin_id: text_custom
empty: true
content: 'No assets available.'
tokenize: false
sorts:
created:
id: created
table: asset_field_data
field: created
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: created
plugin_id: date
order: ASC
expose:
label: ''
field_identifier: created
exposed: false
granularity: second
arguments: { }
filters:
name:
id: name
table: asset_field_data
field: name
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: name
plugin_id: string
operator: contains
value: ''
group: 1
exposed: true
expose:
operator_id: name_op
label: Name
description: ''
use_operator: false
operator: name_op
operator_limit_selection: false
operator_list: { }
identifier: name
required: false
remember: false
multiple: false
remember_roles:
authenticated: authenticated
placeholder: ''
is_grouped: false
group_info:
label: ''
description: ''
identifier: ''
optional: true
widget: select
multiple: false
remember: false
default_group: All
default_group_multiple: { }
group_items: { }
type:
id: type
table: asset_field_data
field: type
relationship: none
group_type: group
admin_label: ''
entity_type: asset
entity_field: type
plugin_id: bundle
operator: in
value: { }
group: 1
exposed: true
expose:
operator_id: type_op
label: 'Asset type'
description: ''
use_operator: false
operator: type_op
operator_limit_selection: false
operator_list: { }
identifier: type
required: false
remember: false
multiple: false
remember_roles:
authenticated: authenticated
reduce: false
is_grouped: false
group_info:
label: ''
description: ''
identifier: ''
optional: true
widget: select
multiple: false
remember: false
default_group: All
default_group_multiple: { }
group_items: { }
filter_groups:
operator: AND
groups:
1: AND
style:
type: table
options:
grouping: { }
row_class: ''
default_row_class: true
columns:
asset_bulk_form: asset_bulk_form
status: status
id: id
name: name
type: type
uid: uid
operations: operations
default: '-1'
info:
asset_bulk_form:
align: ''
separator: ''
empty_column: false
responsive: ''
status:
sortable: true
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
id:
sortable: true
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
name:
sortable: true
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
type:
sortable: true
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
uid:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
operations:
align: ''
separator: ''
empty_column: false
responsive: ''
override: true
sticky: false
summary: ''
empty_table: true
caption: ''
description: ''
row:
type: fields
query:
type: views_query
options:
query_comment: ''
disable_sql_rewrite: false
distinct: false
replica: false
query_tags: { }
relationships: { }
header: { }
footer: { }
display_extenders: { }
cache_metadata:
max-age: 0
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
- user.permissions
tags: { }
collection:
id: collection
display_title: Page
display_plugin: page
position: 1
display_options:
display_extenders: { }
path: admin/content/asset
menu:
type: tab
title: Assets
description: ''
weight: 0
expanded: false
menu_name: admin
parent: ''
context: '0'
tab_options:
type: normal
title: asset
description: ''
weight: 0
cache_metadata:
max-age: 0
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
- user.permissions
tags: { }
@@ -0,0 +1,40 @@
# Schema for the configuration files of the asset module.
asset.type.*:
type: config_entity
label: 'Asset type'
mapping:
id:
type: string
label: 'Machine-readable name'
label:
type: label
label: 'Type'
description:
type: text
label: 'Description'
workflow:
type: string
label: 'Workflow'
new_revision:
type: boolean
label: 'Create new revision'
condition.plugin.asset_type:
type: condition.plugin
mapping:
bundles:
type: sequence
sequence:
type: string
action.configuration.asset_activate_action:
type: action_configuration_default
label: 'Configuration for the asset activate action'
action.configuration.asset_archive_action:
type: action_configuration_default
label: 'Configuration for the asset archive action'
action.configuration.asset_clone_action:
type: action_configuration_default
label: 'Configuration for the asset clone action'
@@ -0,0 +1,36 @@
<?php
namespace Drupal\asset;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\BulkFormEntityListBuilder;
/**
* Defines a class to build a listing of asset entities.
*
* @ingroup asset
*/
class AssetListBuilder extends BulkFormEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['id'] = $this->t('Asset ID');
$header['label'] = $this->t('Label');
$header['type'] = $this->t('Type');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/** @var \Drupal\asset\Entity\AssetInterface $entity */
$row['id'] = ['#markup' => $entity->id()];
$row['name'] = $entity->toLink($entity->label(), 'canonical')->toRenderable();
$row['type'] = ['#markup' => $entity->getBundleLabel()];
return $row + parent::buildRow($entity);
}
}
@@ -0,0 +1,128 @@
<?php
namespace Drupal\asset;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the controller class for assets.
*
* This extends the base storage class, adding required special handling for
* asset entities.
*/
class AssetStorage extends SqlContentEntityStorage {
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* Constructs an AssetStorage object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Database\Connection $database
* The database connection to be used.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* The cache backend to be used.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface $memory_cache
* The memory cache backend to be used.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
*/
public function __construct(EntityTypeInterface $entity_type, Connection $database, EntityFieldManagerInterface $entity_field_manager, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, MemoryCacheInterface $memory_cache, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityTypeManagerInterface $entity_type_manager, TimeInterface $time) {
parent::__construct($entity_type, $database, $entity_field_manager, $cache, $language_manager, $memory_cache, $entity_type_bundle_info, $entity_type_manager);
$this->time = $time;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('database'),
$container->get('entity_field.manager'),
$container->get('cache.entity'),
$container->get('language_manager'),
$container->get('entity.memory_cache'),
$container->get('entity_type.bundle.info'),
$container->get('entity_type.manager'),
$container->get('datetime.time'),
);
}
/**
* {@inheritdoc}
*/
protected function doPreSave(EntityInterface $entity) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$id = parent::doPreSave($entity);
// If there is no original entity, bail.
if (empty($entity->original)) {
return $id;
}
// Load new and original states.
$new_state = $entity->get('status')->first()->getString();
$old_state = $entity->original->get('status')->first()->getString();
$state_unchanged = $new_state == $old_state;
// If the entity is not archived and this would otherwise not be a state
// transition but the archive timestamp is set, then transition to the
// archived state.
if ($state_unchanged && $old_state != 'archived' && $entity->getArchivedTime() != NULL) {
$entity->get('status')->first()->applyTransitionById('archive');
}
// If the entity is archived and this would otherwise not be a state
// transition but the archive timestemp is NULL, then transition to the
// active state.
if ($state_unchanged && $old_state == 'archived' && $entity->getArchivedTime() == NULL) {
$entity->get('status')->first()->applyTransitionById('to_active');
}
// If the state has not changed, bail.
if ($state_unchanged) {
return $id;
}
// If the state has changed to archived and no archived timestamp was
// specified, set it to the current time.
if ($new_state == 'archived' && $entity->getArchivedTime() == NULL) {
$entity->setArchivedTime($this->time->getRequestTime());
}
// Or, if the state has changed from archived, set a null value.
elseif ($old_state == 'archived') {
$entity->setArchivedTime(NULL);
}
return $id;
}
}
@@ -0,0 +1,57 @@
<?php
namespace Drupal\asset;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
/**
* Provides a listing of asset type entities.
*/
class AssetTypeListBuilder extends ConfigEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Asset 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);
}
/**
* {@inheritdoc}
*/
public function getDefaultOperations(EntityInterface $entity) {
$operations = parent::getDefaultOperations($entity);
// Place the edit operation after the operations added by field_ui.module
// which have the weights 15, 20, 25.
if (isset($operations['edit'])) {
$operations['edit']['weight'] = 30;
}
return $operations;
}
/**
* {@inheritdoc}
*/
public function render() {
$build = parent::render();
$build['table']['#empty'] = $this->t('No asset types available. <a href=":link">Add asset type</a>.', [
':link' => Url::fromRoute('entity.asset_type.add_form')->toString(),
]);
return $build;
}
}
@@ -0,0 +1,285 @@
<?php
namespace Drupal\asset\Entity;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\RevisionLogEntityTrait;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\entity\Revision\RevisionableContentEntityBase;
use Drupal\user\EntityOwnerTrait;
/**
* Defines the asset entity.
*
* @ingroup asset
*
* @ContentEntityType(
* id = "asset",
* label = @Translation("Asset"),
* bundle_label = @Translation("Asset type"),
* label_collection = @Translation("Assets"),
* label_singular = @Translation("asset"),
* label_plural = @Translation("assets"),
* label_count = @PluralTranslation(
* singular = "@count asset",
* plural = "@count assets",
* ),
* handlers = {
* "storage" = "Drupal\asset\AssetStorage",
* "access" = "\Drupal\entity\UncacheableEntityAccessControlHandler",
* "list_builder" = "\Drupal\asset\AssetListBuilder",
* "permission_provider" = "\Drupal\entity\UncacheableEntityPermissionProvider",
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "views_data" = "Drupal\views\EntityViewsData",
* "form" = {
* "add" = "Drupal\asset\Form\AssetForm",
* "edit" = "Drupal\asset\Form\AssetForm",
* "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
* "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
* },
* "route_provider" = {
* "default" = "Drupal\entity\Routing\AdminHtmlRouteProvider",
* "revision" = "\Drupal\entity\Routing\RevisionRouteProvider",
* },
* "local_task_provider" = {
* "default" = "\Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
* },
* },
* base_table = "asset",
* data_table = "asset_field_data",
* revision_table = "asset_revision",
* translatable = TRUE,
* revisionable = TRUE,
* show_revision_ui = TRUE,
* admin_permission = "administer assets",
* entity_keys = {
* "id" = "id",
* "revision" = "revision_id",
* "bundle" = "type",
* "label" = "name",
* "owner" = "uid",
* "uuid" = "uuid",
* "langcode" = "langcode",
* },
* bundle_entity_type = "asset_type",
* field_ui_base_route = "entity.asset_type.edit_form",
* common_reference_target = TRUE,
* permission_granularity = "bundle",
* links = {
* "canonical" = "/asset/{asset}",
* "add-page" = "/asset/add",
* "add-form" = "/asset/add/{asset_type}",
* "collection" = "/admin/content/asset",
* "delete-form" = "/asset/{asset}/delete",
* "delete-multiple-form" = "/asset/delete",
* "edit-form" = "/asset/{asset}/edit",
* "revision" = "/asset/{asset}/revisions/{asset_revision}/view",
* "revision-revert-form" = "/asset/{asset}/revisions/{asset_revision}/revert",
* "version-history" = "/asset/{asset}/revisions",
* },
* revision_metadata_keys = {
* "revision_user" = "revision_user",
* "revision_created" = "revision_created",
* "revision_log_message" = "revision_log_message"
* },
* )
*/
class Asset extends RevisionableContentEntityBase implements AssetInterface {
use EntityChangedTrait;
use EntityOwnerTrait;
use RevisionLogEntityTrait;
/**
* {@inheritdoc}
*/
public function label() {
return $this->getName();
}
/**
* {@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 getArchivedTime() {
return $this->get('archived')->value;
}
/**
* {@inheritdoc}
*/
public function setArchivedTime($timestamp) {
$this->set('archived', $timestamp);
return $this;
}
/**
* {@inheritdoc}
*/
public function getBundleLabel() {
/** @var \Drupal\asset\Entity\AssetTypeInterface $type */
$type = $this->entityTypeManager()
->getStorage('asset_type')
->load($this->bundle());
return $type->label();
}
/**
* {@inheritdoc}
*/
public static function getCurrentUserId() {
return [\Drupal::currentUser()->id()];
}
/**
* {@inheritdoc}
*/
public static function getRequestTime() {
return \Drupal::time()->getRequestTime();
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::ownerBaseFieldDefinitions($entity_type);
$fields += static::revisionLogBaseFieldDefinitions($entity_type);
$fields['name'] = BaseFieldDefinition::create('string')
->setLabel(t('Name'))
->setDescription(t('The name of the asset.'))
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setRequired(TRUE)
->setSetting('max_length', 255)
->setSetting('text_processing', 0)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE);
$fields['status'] = BaseFieldDefinition::create('state')
->setLabel(t('Status'))
->setDescription(t('Indicates the status of the asset.'))
->setRevisionable(TRUE)
->setRequired(TRUE)
->setSetting('max_length', 255)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'state_transition_form',
'weight' => 10,
])
->setDisplayOptions('form', [
'type' => 'options_select',
'weight' => 11,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE)
->setSetting('workflow_callback', ['\Drupal\asset\Entity\Asset', 'getWorkflowId']);
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setDescription(t('The user ID of author of the asset.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setDefaultValueCallback('Drupal\asset\Entity\Asset::getCurrentUserId')
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'author',
'weight' => 0,
])
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => 12,
'settings' => [
'match_operator' => 'CONTAINS',
'size' => '60',
'autocomplete_type' => 'tags',
'placeholder' => '',
],
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Authored on'))
->setDescription(t('The time that the asset was created.'))
->setRevisionable(TRUE)
->setDefaultValueCallback(static::class . '::getRequestTime')
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'timestamp',
'weight' => 0,
])
->setDisplayOptions('form', [
'type' => 'datetime_timestamp',
'weight' => 13,
])
->setDisplayConfigurable('form', TRUE);
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time the asset was last edited.'))
->setRevisionable(TRUE);
$fields['archived'] = BaseFieldDefinition::create('timestamp')
->setLabel(t('Timestamp'))
->setDescription(t('The time the asset was archived.'))
->setRevisionable(TRUE);
return $fields;
}
/**
* Gets the workflow ID for the state field.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset entity.
*
* @return string
* The workflow ID.
*/
public static function getWorkflowId(AssetInterface $asset) {
$workflow = AssetType::load($asset->bundle())->getWorkflowId();
return $workflow;
}
}
@@ -0,0 +1,82 @@
<?php
namespace Drupal\asset\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface for defining asset entities.
*
* @ingroup asset
*/
interface AssetInterface extends ContentEntityInterface, EntityChangedInterface, RevisionLogInterface, EntityOwnerInterface {
/**
* Gets the asset name.
*
* @return string
* The asset name.
*/
public function getName();
/**
* Sets the asset name.
*
* @param string $name
* The asset name.
*
* @return \Drupal\asset\Entity\AssetInterface
* The asset entity.
*/
public function setName($name);
/**
* Gets the asset creation timestamp.
*
* @return int
* Creation timestamp of the asset.
*/
public function getCreatedTime();
/**
* Sets the asset creation timestamp.
*
* @param int $timestamp
* Creation timestamp of the asset.
*
* @return \Drupal\asset\Entity\AssetInterface
* The asset entity.
*/
public function setCreatedTime($timestamp);
/**
* Gets the asset archived timestamp.
*
* @return int
* Archived timestamp of the asset.
*/
public function getArchivedTime();
/**
* Sets the asset archived timestamp.
*
* @param int $timestamp
* Archived timestamp of the asset.
*
* @return \Drupal\asset\Entity\AssetInterface
* The asset entity.
*/
public function setArchivedTime($timestamp);
/**
* Gets the label of the the asset type.
*
* @return string
* The label of the asset type.
*/
public function getBundleLabel();
}
@@ -0,0 +1,178 @@
<?php
namespace Drupal\asset\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\Core\Entity\EntityStorageInterface;
/**
* Defines the asset type entity.
*
* @ConfigEntityType(
* id = "asset_type",
* label = @Translation("Asset type"),
* label_collection = @Translation("Asset types"),
* label_singular = @Translation("Asset type"),
* label_plural = @Translation("Asset types"),
* label_count = @PluralTranslation(
* singular = "@count asset type",
* plural = "@count asset types",
* ),
* handlers = {
* "list_builder" = "Drupal\asset\AssetTypeListBuilder",
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "form" = {
* "add" = "Drupal\asset\Form\AssetTypeForm",
* "edit" = "Drupal\asset\Form\AssetTypeForm",
* "delete" = "\Drupal\Core\Entity\EntityDeleteForm",
* },
* "route_provider" = {
* "default" = "Drupal\entity\Routing\DefaultHtmlRouteProvider",
* },
* },
* admin_permission = "administer asset types",
* config_prefix = "type",
* bundle_of = "asset",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* "uuid" = "uuid"
* },
* links = {
* "canonical" = "/admin/structure/asset-type/{asset_type}",
* "add-form" = "/admin/structure/asset-type/add",
* "edit-form" = "/admin/structure/asset-type/{asset_type}/edit",
* "delete-form" = "/admin/structure/asset-type/{asset_type}/delete",
* "collection" = "/admin/structure/asset-type"
* },
* config_export = {
* "id",
* "label",
* "description",
* "workflow",
* "new_revision",
* }
* )
*/
class AssetType extends ConfigEntityBundleBase implements AssetTypeInterface {
/**
* The asset type ID.
*
* @var string
*/
protected $id;
/**
* The asset type label.
*
* @var string
*/
protected $label;
/**
* A brief description of this asset type.
*
* @var string
*/
protected $description;
/**
* The asset type workflow ID.
*
* @var string
*/
protected $workflow;
/**
* Default value of the 'Create new revision' checkbox of the asset type.
*
* @var bool
*/
protected $new_revision = TRUE;
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->description;
}
/**
* {@inheritdoc}
*/
public function setDescription($description) {
return $this->set('description', $description);
}
/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
// If the asset type id changed, update all existing assets of that type.
if ($update && $this->getOriginalId() != $this->id()) {
$update_count = $this->entityTypeManager()->getStorage('asset')->updateType($this->getOriginalId(), $this->id());
if ($update_count) {
\Drupal::messenger()->addMessage(\Drupal::translation()->formatPlural($update_count,
'Changed the asset type of 1 post from %old-type to %type.',
'Changed the asset type of @count posts from %old-type to %type.',
[
'%old-type' => $this->getOriginalId(),
'%type' => $this->id(),
]));
}
}
if ($update) {
// Clear the cached field definitions as some settings affect the field
// definitions.
$this->entityTypeManager()->clearCachedDefinitions();
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
}
}
/**
* {@inheritdoc}
*/
public function getWorkflowId() {
return $this->workflow;
}
/**
* {@inheritdoc}
*/
public function setWorkflowId($workflow_id) {
$this->workflow = $workflow_id;
return $this;
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
parent::calculateDependencies();
// The asset type must depend on the module that provides the workflow.
$workflow_manager = \Drupal::service('plugin.manager.workflow');
$workflow = $workflow_manager->createInstance($this->getWorkflowId());
$this->calculatePluginDependencies($workflow);
return $this;
}
/**
* {@inheritdoc}
*/
public function shouldCreateNewRevision() {
return $this->new_revision;
}
/**
* {@inheritdoc}
*/
public function setNewRevision($new_revision) {
return $this->set('new_revision', $new_revision);
}
}
@@ -0,0 +1,12 @@
<?php
namespace Drupal\asset\Entity;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\EntityDescriptionInterface;
use Drupal\Core\Entity\RevisionableEntityBundleInterface;
/**
* Provides an interface for defining asset type entities.
*/
interface AssetTypeInterface extends ConfigEntityInterface, EntityDescriptionInterface, RevisionableEntityBundleInterface {}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\asset\Event;
use Drupal\Component\EventDispatcher\Event;
use Drupal\asset\Entity\AssetInterface;
/**
* Event that is fired by asset save, delete and clone operations.
*/
class AssetEvent extends Event {
const PRESAVE = 'asset_presave';
const INSERT = 'asset_insert';
const UPDATE = 'asset_update';
const DELETE = 'asset_delete';
/**
* The Asset entity.
*
* @var \Drupal\asset\Entity\AssetInterface
*/
public AssetInterface $asset;
/**
* Constructs the object.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The Asset entity.
*/
public function __construct(AssetInterface $asset) {
$this->asset = $asset;
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\asset\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for asset entities.
*
* @ingroup asset
*/
class AssetForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$status = parent::save($form, $form_state);
$entity_url = $this->entity->toUrl()->setAbsolute()->toString();
$this->messenger()->addMessage($this->t('Saved asset: <a href=":url">%label</a>', [':url' => $entity_url, '%label' => $this->entity->label()]));
$form_state->setRedirectUrl($this->entity->toUrl());
return $status;
}
}
@@ -0,0 +1,115 @@
<?php
namespace Drupal\asset\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\state_machine\WorkflowManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Form controller for asset type entities.
*
* @package Drupal\asset\Form
*/
class AssetTypeForm extends EntityForm {
/**
* The workflow manager.
*
* @var \Drupal\state_machine\WorkflowManagerInterface
*/
protected $workflowManager;
/**
* Constructs a new AssetTypeForm object.
*
* @param \Drupal\state_machine\WorkflowManagerInterface $workflow_manager
* The workflow manager.
*/
public function __construct(WorkflowManagerInterface $workflow_manager) {
$this->workflowManager = $workflow_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.workflow')
);
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$asset_type = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $asset_type->label(),
'#description' => $this->t('Label for the asset type.'),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $asset_type->id(),
'#machine_name' => [
'exists' => '\Drupal\asset\Entity\AssetType::load',
],
'#disabled' => !$asset_type->isNew(),
];
$form['description'] = [
'#type' => 'textarea',
'#title' => $this->t('Description'),
'#default_value' => $asset_type->getDescription(),
];
$form['workflow'] = [
'#type' => 'select',
'#title' => $this->t('Workflow'),
'#options' => $this->workflowManager->getGroupedLabels('asset'),
'#default_value' => $asset_type->getWorkflowId(),
'#description' => $this->t('Used by all assets of this type.'),
];
$form['new_revision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Create new revision'),
'#default_value' => $asset_type->shouldCreateNewRevision(),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$asset_type = $this->entity;
$status = $asset_type->save();
switch ($status) {
case SAVED_NEW:
$this->messenger()->addMessage($this->t('Created the %label asset type.', [
'%label' => $asset_type->label(),
]));
break;
default:
$this->messenger()->addMessage($this->t('Saved the %label asset type.', [
'%label' => $asset_type->label(),
]));
}
$form_state->setRedirectUrl($asset_type->toUrl('collection'));
return $status;
}
}
@@ -0,0 +1,21 @@
<?php
namespace Drupal\asset\Plugin\Action;
/**
* Action that makes an asset active.
*
* @Action(
* id = "asset_activate_action",
* label = @Translation("Makes an Asset active"),
* type = "asset"
* )
*/
class AssetActivate extends AssetStateChangeBase {
/**
* {@inheritdoc}
*/
protected $targetState = 'active';
}
@@ -0,0 +1,21 @@
<?php
namespace Drupal\asset\Plugin\Action;
/**
* Action that archives an asset.
*
* @Action(
* id = "asset_archive_action",
* label = @Translation("Archive an asset"),
* type = "asset"
* )
*/
class AssetArchive extends AssetStateChangeBase {
/**
* {@inheritdoc}
*/
protected $targetState = 'archived';
}
@@ -0,0 +1,86 @@
<?php
namespace Drupal\asset\Plugin\Action;
use Drupal\Core\Action\Plugin\Action\EntityActionBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\asset\Entity\AssetInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Action that clones an asset.
*
* @Action(
* id = "asset_clone_action",
* label = @Translation("Clone an asset"),
* type = "asset"
* )
*/
class AssetClone extends EntityActionBase {
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs an AssetClone object.
*
* @param mixed[] $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\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('current_user'),
);
}
/**
* {@inheritdoc}
*/
public function execute(?AssetInterface $asset = NULL) {
if ($asset) {
$cloned_asset = $asset->createDuplicate();
$cloned_asset->setOwnerId($this->currentUser->id());
$new_name = $asset->getName() . ' ' . $this->t('(clone of asset #@id)', ['@id' => $asset->id()]);
$cloned_asset->setName($new_name);
$cloned_asset->save();
$this->messenger()->addMessage($this->t('Asset saved: <a href=":uri">%asset_label</a>', [':uri' => $cloned_asset->toUrl()->toString(), '%asset_label' => $cloned_asset->label()]));
}
}
/**
* {@inheritdoc}
*/
public function access($object, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
/** @var \Drupal\asset\Entity\AssetInterface $object */
$result = $object->access('view', $account, TRUE)
->andIf($object->access('create', $account, TRUE));
return $return_as_object ? $result : $result->isAllowed();
}
}
@@ -0,0 +1,99 @@
<?php
namespace Drupal\asset\Plugin\Action;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\Plugin\Action\EntityActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\asset\Entity\AssetInterface;
/**
* Base class for actions that change the asset status state.
*/
abstract class AssetStateChangeBase extends EntityActionBase {
/**
* The target state to transition to.
*
* @var string
*/
protected $targetState;
/**
* {@inheritdoc}
*/
public function execute(?AssetInterface $asset = NULL) {
// Bail if there is no asset.
if (empty($asset)) {
return;
}
// Apply the transition to target state if not already the current state.
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $asset->get('status')->first();
if ($state_item->getOriginalId() !== $this->targetState && $transition = $state_item->getWorkflow()->findTransition($state_item->getOriginalId(), $this->targetState)) {
$state_item->applyTransition($transition);
$asset->setNewRevision(TRUE);
// Validate the entity before saving.
$violations = $asset->validate();
if ($violations->count() > 0) {
$this->messenger()->addWarning(
$this->t('Could not change the status of <a href=":entity_link">%entity_label</a>: validation failed.',
[
':entity_link' => $asset->toUrl()->setAbsolute()->toString(),
'%entity_label' => $asset->label(),
],
),
);
return;
}
$asset->save();
}
}
/**
* {@inheritdoc}
*/
public function access($object, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
/** @var \Drupal\asset\Entity\AssetInterface $object */
// First check entity and state field access.
$result = $object->get('status')->access('edit', $account, TRUE)
->andIf($object->access('update', $account, TRUE));
// Save the state field.
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $object->get('status')->first();
// If the state field is already in the target state, return early.
// The workflow will not allow a transition to the same state but the
// action itself does not need to fail.
if ($state_item->getOriginalId() === $this->targetState) {
return $return_as_object ? $result : $result->isAllowed();
}
// Check that the target state exists for the workflow.
$workflow = $state_item->getWorkflow();
$target_state = $workflow->getState($this->targetState);
// Deny access if the workflow does not support the target state.
if (empty($target_state)) {
$result = $result->orIf(AccessResult::forbidden(
$this->t('The %workflow workflow does not support the %target_state state.', ['%workflow' => $workflow->getLabel(), '%target_state' => $this->targetState]),
));
}
// Else check that a transition exists to the desired target state.
else {
$transition = $workflow->findTransition($state_item->getOriginalId(), $this->targetState);
$result = $result->orIf(AccessResult::forbiddenIf(
empty($transition) || !$state_item->isTransitionAllowed($transition->getId()),
$this->t('The state transition from %original_state to %target_state is not allowed.', ['%original' => $state_item->getOriginalLabel(), '%target_state' => $target_state->getLabel()]),
));
}
return $return_as_object ? $result : $result->isAllowed();
}
}
@@ -0,0 +1,78 @@
<?php
namespace Drupal\asset\Plugin\migrate\source\d7;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;
/**
* Asset source from database.
*
* @MigrateSource(
* id = "d7_asset",
* source_module = "farm_asset"
* )
*
* @deprecated in farm:3.0.0 and is removed from farm:4.0.0. Support for farmOS
* v1 migrations was dropped in farmOS 3.x.
* @see https://www.drupal.org/project/farm/issues/3410701
* @see https://www.drupal.org/project/farm/issues/3382616
*/
class Asset extends FieldableEntity {
/**
* {@inheritdoc}
*/
public function query() {
$query = $this->select('farm_asset', 'fa')
->fields('fa')
->distinct()
->orderBy('id');
if (isset($this->configuration['bundle'])) {
$query->condition('fa.type', (array) $this->configuration['bundle'], 'IN');
}
return $query;
}
/**
* {@inheritdoc}
*/
public function fields() {
$fields = [
'id' => $this->t('The asset ID'),
'name' => $this->t('The asset name'),
'type' => $this->t('The asset type'),
'uid' => $this->t('The asset author ID'),
'created' => $this->t('Timestamp when the asset was created'),
'changed' => $this->t('Timestamp when the asset was last modified'),
'archived' => $this->t('Timestamp when the asset was archived'),
];
return $fields;
}
/**
* {@inheritdoc}
*/
public function prepareRow(Row $row) {
$id = $row->getSourceProperty('id');
$type = $row->getSourceProperty('type');
// Get Field API field values.
foreach ($this->getFields('farm_asset', $type) as $field_name => $field) {
$row->setSourceProperty($field_name, $this->getFieldValues('farm_asset', $field_name, $id));
}
return parent::prepareRow($row);
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['id']['type'] = 'integer';
return $ids;
}
}
@@ -0,0 +1,22 @@
{#
/**
* @file asset.html.twig
* Default theme implementation to present asset data.
*
* This template is used when viewing asset 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_asset()
*
* @ingroup themeable
*/
#}
<div{{ attributes.addClass('asset') }}>
{% if content %}
{{- content -}}
{% endif %}
</div>
@@ -0,0 +1,7 @@
name: Asset module tests
description: Support module for asset testing.
type: module
package: Testing
core_version_requirement: ^10
dependencies:
- farm:asset
@@ -0,0 +1,6 @@
id: default
label: default
description: 'Test asset type'
langcode: en
workflow: asset_default
new_revision: TRUE
@@ -0,0 +1,46 @@
langcode: en
status: true
dependencies:
module:
- asset
- datetime
- options
- user
id: asset_test_view
label: 'asset test view'
module: views
description: ''
tag: ''
base_table: asset_field_data
base_field: id
display:
default:
display_options:
defaults:
fields: false
pager: false
sorts: false
row:
type: fields
fields:
id:
id: id
table: asset_field_data
field: id
relationship: none
entity_type: asset
entity_field: id
plugin_id: field
name:
id: name
table: asset_field_data
field: name
relationship: none
entity_type: asset
entity_field: name
plugin_id: field
sorts: { }
display_plugin: default
display_title: Master
id: default
position: 0
@@ -0,0 +1,177 @@
<?php
namespace Drupal\Tests\asset\Functional;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\asset\Entity\Asset;
/**
* Tests the asset CRUD.
*
* @group farm
*/
class AssetCRUDTest extends AssetTestBase {
use StringTranslationTrait;
/**
* Run all tests.
*/
public function testAll() {
$this->doTestFieldsVisibility();
$this->doTestCreateAsset();
$this->doTestViewAsset();
$this->doTestEditAsset();
$this->doTestDeleteAsset();
$this->doTestArchiveAsset();
$this->doTestArchiveAssetViaTimestamp();
}
/**
* Fields are displayed correctly.
*/
public function doTestFieldsVisibility() {
$this->drupalGet('asset/add/default');
$assert_session = $this->assertSession();
$assert_session->statusCodeEquals(200);
$assert_session->fieldExists('name[0][value]');
$assert_session->fieldExists('status');
$assert_session->fieldExists('revision_log_message[0][value]');
$assert_session->fieldExists('uid[0][target_id]');
$assert_session->fieldExists('created[0][value][date]');
$assert_session->fieldExists('created[0][value][time]');
}
/**
* Create asset entity.
*/
public function doTestCreateAsset() {
$assert_session = $this->assertSession();
$name = $this->randomMachineName();
$edit = [
'name[0][value]' => $name,
];
$this->drupalGet('asset/add/default');
$this->submitForm($edit, 'Save');
$result = \Drupal::entityTypeManager()
->getStorage('asset')
->getQuery()
->accessCheck(TRUE)
->range(0, 1)
->execute();
$asset_id = reset($result);
$asset = Asset::load($asset_id);
$this->assertEquals($asset->get('name')->value, $name, 'asset has been saved.');
$assert_session->pageTextContains("Saved asset: $name");
$assert_session->pageTextContains($name);
}
/**
* Display asset entity.
*/
public function doTestViewAsset() {
$edit = [
'name' => $this->randomMachineName(),
'created' => \Drupal::time()->getRequestTime(),
];
$asset = $this->createAssetEntity($edit);
$asset->save();
$this->drupalGet($asset->toUrl('canonical'));
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains($edit['name']);
$this->assertSession()->responseContains(\Drupal::service('date.formatter')->format(\Drupal::time()->getRequestTime()));
}
/**
* Edit asset entity.
*/
public function doTestEditAsset() {
$asset = $this->createAssetEntity();
$asset->save();
$edit = [
'name[0][value]' => $this->randomMachineName(),
];
$this->drupalGet($asset->toUrl('edit-form'));
$this->submitForm($edit, 'Save');
$this->assertSession()->pageTextContains($edit['name[0][value]']);
}
/**
* Delete asset entity.
*/
public function doTestDeleteAsset() {
$asset = $this->createAssetEntity();
$asset->save();
$label = $asset->getName();
$asset_id = $asset->id();
$this->drupalGet($asset->toUrl('delete-form'));
$this->submitForm([], 'Delete');
$this->assertSession()->responseContains($this->t('The @entity-type %label has been deleted.', [
'@entity-type' => $asset->getEntityType()->getSingularLabel(),
'%label' => $label,
]));
$this->assertNull(Asset::load($asset_id));
}
/**
* Asset archiving.
*/
public function doTestArchiveAsset() {
$asset = $this->createAssetEntity();
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'active', 'New assets are active by default');
$this->assertNull($asset->getArchivedTime(), 'Archived timestamp is null by default');
$asset->get('status')->first()->applyTransitionById('archive');
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'archived', 'Assets can be archived');
$this->assertNotNull($asset->getArchivedTime(), 'Archived timestamp is saved');
$asset->get('status')->first()->applyTransitionById('to_active');
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'active', 'Assets can be made active');
$this->assertNull($asset->getArchivedTime(), 'Asset made active has a null timestamp');
$asset->get('status')->first()->applyTransitionById('archive');
$asset->setArchivedTime('2021-07-17T19:45:49+00:00');
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'archived', 'Assets can be archived with explicit timestamp');
$this->assertEquals($asset->getArchivedTime(), '2021-07-17T19:45:49+00:00', 'Explicit archived timestamp is saved');
}
/**
* Asset archiving/unarchiving via timestamp.
*/
public function doTestArchiveAssetViaTimestamp() {
$asset = $this->createAssetEntity();
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'active', 'New assets are active by default');
$this->assertNull($asset->getArchivedTime(), 'Archived timestamp is null by default');
$asset->setArchivedTime('2021-07-17T19:45:49+00:00');
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'archived', 'Assets can be archived');
$this->assertEquals($asset->getArchivedTime(), '2021-07-17T19:45:49+00:00', 'Archived timestamp is saved');
$asset->setArchivedTime(NULL);
$asset->save();
$this->assertEquals($asset->get('status')->first()->getString(), 'active', 'Assets can be made active');
$this->assertNull($asset->getArchivedTime(), 'Asset made active has a null timestamp');
}
}
@@ -0,0 +1,82 @@
<?php
namespace Drupal\Tests\asset\Functional;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
/**
* Tests the asset CRUD.
*/
abstract class AssetTestBase extends FarmBrowserTestBase {
/**
* Modules to install.
*
* @var array
*/
protected static $modules = [
'asset',
'asset_test',
'entity',
'user',
'field',
'text',
];
/**
* A test user with administrative privileges.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->adminUser = $this->drupalCreateUser($this->getAdministratorPermissions());
$this->drupalLogin($this->adminUser);
drupal_flush_all_caches();
}
/**
* Gets the permissions for the admin user.
*
* @return string[]
* The permissions.
*/
protected function getAdministratorPermissions() {
return [
'access administration pages',
'administer assets',
'view any asset',
'create default asset',
'view any default asset',
'update own default asset',
'update any default asset',
'delete own default asset',
'delete any default asset',
];
}
/**
* Creates a asset entity.
*
* @param array $values
* Array of values to feed the entity.
*
* @return \Drupal\asset\Entity\AssetInterface
* The asset entity.
*/
protected function createAssetEntity(array $values = []) {
$storage = \Drupal::service('entity_type.manager')->getStorage('asset');
$entity = $storage->create($values + [
'name' => $this->randomMachineName(),
'created' => \Drupal::time()->getRequestTime(),
'type' => 'default',
]);
return $entity;
}
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\asset\Traits;
use Drupal\asset\Entity\Asset;
/**
* Provides methods to create asset entities.
*
* This trait is meant to be used only by test classes.
*/
trait AssetCreationTrait {
/**
* Creates an asset entity.
*
* @param array $values
* Array of values to feed the entity.
*
* @return \Drupal\asset\Entity\AssetInterface
* The asset entity.
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function createAssetEntity(array $values = []) {
/** @var \Drupal\asset\Entity\AssetInterface $entity */
$entity = Asset::create($values + [
'name' => $this->randomMachineName(),
'type' => 'default',
]);
$entity->save();
return $entity;
}
}
@@ -0,0 +1,7 @@
name: farmOS Comment
description: Adds support for comments on farmOS entities.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- drupal:comment
@@ -0,0 +1,3 @@
farm_comment:
permission_callbacks:
- Drupal\farm_comment\CommentPermissions::permissions
@@ -0,0 +1,129 @@
<?php
/**
* @file
* Contains farm_comment.module.
*/
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\entity\BundleFieldDefinition;
/**
* Helper function for generating a standard comment base field definition.
*
* @param string $entity_type
* The entity type.
*
* @return \Drupal\Core\Field\BaseFieldDefinition
* Returns a comment base field definition.
*/
function farm_comment_base_field_definition(string $entity_type) {
// Create a new comment field definition.
// We use BundleFieldDefinition instead of BaseFieldDefinition to force Drupal
// to create a separate database table for this field. Otherwise, if it is
// added to the base table then the comment field default value is always 0
// (CommentItemInterface::HIDDEN) instead of 2 (CommentItemInterface::OPEN),
// because the Drupal\comment\Plugin\Field\FieldType\CommentItem::schema()
// default is 0.
$field = BundleFieldDefinition::create('comment');
// Set the field label.
$field->setLabel(t('Comments'));
// We assume that the comment type matches the entity type.
$field->setSetting('comment_type', $entity_type);
// Disable previews.
$field->setSetting('preview', 0);
// A default value must be set for comment fields.
// Enable comments on entities by default.
$default_value = [
[
'status' => CommentItemInterface::OPEN,
'cid' => 0,
'last_comment_timestamp' => 0,
'last_comment_name' => '',
'last_comment_uid' => 0,
'comment_count' => 0,
],
];
$field->setDefaultValue($default_value);
// Build form display settings.
$field->setDisplayOptions('form', [
'type' => 'comment_default',
'weight' => 450,
]);
// Build view display settings.
// Display comments on the bottom of entity view displays by default, with the
// field label above them.
$field->setDisplayOptions('view', [
'label' => 'above',
'type' => 'comment_default',
'weight' => 1000,
]);
return $field;
}
/**
* Implements hook_entity_form_display_alter().
*/
function farm_comment_entity_form_display_alter(EntityFormDisplayInterface $form_display, array $context) {
$comment_bundles = ['asset', 'log', 'plan'];
if ($form_display->getTargetEntityTypeId() == 'comment' && in_array($context['bundle'], $comment_bundles) && $form_display->getMode() == 'default' && $form_display->isNew()) {
$form_display->setComponent('author', [
'region' => 'content',
'settings' => [],
'weight' => 0,
]);
$form_display->setComponent('comment_body', [
'type' => 'text_textarea',
'region' => 'content',
'settings' => [
'rows' => 5,
'placeholder' => '',
],
'weight' => 1,
]);
$form_display->removeComponent('subject');
}
}
/**
* Implements hook_entity_view_display_alter().
*/
function farm_comment_entity_view_display_alter(EntityViewDisplayInterface $display, array $context) {
$comment_bundles = ['asset', 'log', 'plan'];
$display_modes = ['default', 'full'];
if ($context['entity_type'] == 'comment' && in_array($context['bundle'], $comment_bundles) && in_array($display->getMode(), $display_modes) && $display->isNew()) {
$display->setComponent('comment_body', [
'type' => 'text_default',
'label' => 'hidden',
'region' => 'content',
'settings' => [],
'weight' => 0,
]);
$display->setComponent('links', [
'region' => 'content',
'settings' => [],
'weight' => 1,
]);
}
}
/**
* Implements hook_farm_ui_theme_region_items().
*/
function farm_comment_farm_ui_theme_region_items(string $entity_type) {
return [
'bottom' => [
'comment',
],
];
}
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_comment_asset
id: asset
label: 'Asset comment'
target_entity_type_id: asset
description: ''
@@ -0,0 +1,23 @@
langcode: en
status: true
dependencies:
config:
- comment.type.asset
- field.storage.comment.comment_body
enforced:
module:
- farm_comment_asset
module:
- text
id: comment.asset.comment_body
field_name: comment_body
entity_type: comment
bundle: asset
label: Comment
description: ''
required: true
translatable: true
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long
@@ -0,0 +1,8 @@
name: Asset comments
description: Enables comments on farmOS assets.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- farm:asset
- farm:farm_comment
@@ -0,0 +1,22 @@
<?php
/**
* @file
* Contains farm_comment_asset.module.
*/
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_entity_base_field_info().
*/
function farm_comment_asset_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
// Add comment base field to assets.
if ($entity_type->id() == 'asset') {
$fields['comment'] = farm_comment_base_field_definition('asset');
}
return $fields;
}
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_comment_log
id: log
label: 'Log comment'
target_entity_type_id: log
description: ''
@@ -0,0 +1,23 @@
langcode: en
status: true
dependencies:
config:
- comment.type.log
- field.storage.comment.comment_body
enforced:
module:
- farm_comment_log
module:
- text
id: comment.log.comment_body
field_name: comment_body
entity_type: comment
bundle: log
label: Comment
description: ''
required: true
translatable: true
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long
@@ -0,0 +1,8 @@
name: Log comments
description: Enables comments on farmOS logs.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- farm:farm_comment
- log:log
@@ -0,0 +1,22 @@
<?php
/**
* @file
* Contains farm_comment_log.module.
*/
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_entity_base_field_info().
*/
function farm_comment_log_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
// Add comment base field to logs.
if ($entity_type->id() == 'log') {
$fields['comment'] = farm_comment_base_field_definition('log');
}
return $fields;
}
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_comment_plan
id: plan
label: 'Plan comment'
target_entity_type_id: plan
description: ''
@@ -0,0 +1,23 @@
langcode: en
status: true
dependencies:
config:
- comment.type.plan
- field.storage.comment.comment_body
enforced:
module:
- farm_comment_plan
module:
- text
id: comment.plan.comment_body
field_name: comment_body
entity_type: comment
bundle: plan
label: Comment
description: ''
required: true
translatable: true
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long
@@ -0,0 +1,8 @@
name: Plan comments
description: Enables comments on farmOS plans.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- farm:farm_comment
- farm:plan
@@ -0,0 +1,22 @@
<?php
/**
* @file
* Contains farm_comment_plan.module.
*/
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_entity_base_field_info().
*/
function farm_comment_plan_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
// Add comment base field to plans.
if ($entity_type->id() == 'plan') {
$fields['comment'] = farm_comment_base_field_definition('plan');
}
return $fields;
}
@@ -0,0 +1,45 @@
<?php
namespace Drupal\farm_comment;
use Drupal\user\RoleInterface;
/**
* Add comment permissions to managed farmOS roles.
*/
class CommentPermissions {
/**
* Add permissions to role.
*
* @param \Drupal\user\RoleInterface $role
* The role to add permissions to.
*
* @return array
* An array of permission strings.
*/
public function permissions(RoleInterface $role) {
$perms = [];
// Load farm_role access rules from third-party settings. Bail if empty.
$access = $role->getThirdPartySetting('farm_role', 'access');
if (empty($access)) {
return $perms;
}
// If the role has "view all" access, allow viewing comments.
if (!empty($access['entity']['view all'])) {
$perms[] = 'access comments';
}
// If the role has "edit all" access, allow posting/editing comments.
if (!empty($access['entity']['update all'])) {
$perms[] = 'post comments';
$perms[] = 'skip comment approval';
$perms[] = 'edit own comments';
}
return $perms;
}
}
@@ -0,0 +1,7 @@
name: farmOS CSV
description: Provides CSV features for farmOS.
type: module
package: farmOS
core_version_requirement: ^10
dependencies:
- csv_serialization:csv_serialization
Loaded 100 of 31193 files, more files were not shown because too many files have changed in this diff. Show more