SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
Typed Data
in Drupal 8
Drupal Cafe Kiev - 22.12.16
hello!
I am Igor Karpilenko
Drupal developer from Deweb studio
https://www.drupal.org/u/hamrant
https://www.facebook.com/hamrant
https://www.linkedin.com/in/hamrant
Prehistory
The problem
PHP is a very loosely typed language. It doesn’t have a clear definition of
the different types of data it deals with.
Therefore Drupal used to be the same. For example, there was no
consistent way of telling if a field value is a string, an integer or a
timestamp.
Typed Data
The Typed Data API was created to provide developers with a
consistent way of interacting with data in different ways.
Not only does the API allow you to interact with the actual data, it also
provides means of fetching more information, or metadata, about the
actual data.
The Typed Data API is a low level, generic and reusable object oriented
API that appears at multiple levels of the Drupal 8 architecture.
Take for example, the EntityAdapter, which extends TypedData and
acts as a wrapper for an Entity. Or FieldItemBase, which is an
unwrapped extension of TypedData.
Each data type in the Typed Data API is a plugin class (annotation class
example: DrupalCoreTypedDataAnnotationDataType).
These plugins are managed by the typed_data_manager service (by
default DrupalCoreTypedDataTypedDataManager).
Each data object encapsulates a single piece of data, provides access
to the metadata, and provides validation capability.
Where to look?
core/lib/Drupal/Core/TypedData
The Typed Data API interfaces
List
Data
Primitive
Data
Complex
Data
Primitive Data
Implementations of this interface are used for something that
represents a single piece of typed data, like a string or integer.
This is the smallest building block in the Typed Data API.
BinaryData
BooleanData
Email
FloatData
IntegerData
StringData
DateTimeIso8601 - DateTimeInterface
DurationIso8601 - DurationInterface
TimeSpan - DurationInterface
Timestamp - DateTimeInterface
Primitive data types
PrimitiveInterface methods
getValue() - Gets the primitive data value
setValue($value) - Sets the primitive data value
getCastedValue() - Gets the primitive data value casted to the
correct PHP type
Primitive data type example
/**
* The integer data type.
*
* The plain value of an integer is a regular PHP integer. For setting the value
* any PHP variable that casts to an integer may be passed.
*
* @DataType(
* id = "integer",
* label = @Translation("Integer")
* )
*/
class IntegerData extends PrimitiveBase implements IntegerInterface
/**
* {@inheritdoc}
*/
public function getCastedValue() {
return (int) $this->value;
}
}
create a typed data object in code
First get the typed_data_manager service from the container or by
calling Drupal::typedDataManager().
Then pass the plugin ID to $manager::createDataDefinition() to
create an appropriate data definition object.
Then pass the data definition object and the value of the data to
$manager::create() to create a typed data object.
$definition = DataDefinition::create('integer');
$int = Drupal::typedDataManager()->create($definition);
$int->setValue('10');
$validation = $int->validate();
$raw_data = $int->getValue();
$int_data = $int->getCastedValue();
$raw_data_type = gettype($raw_data);
$int_data_type = gettype($int_data);
Integer data type usage example
Constraints
The Data Definition class can set constraints upon the Typed Data
object.
Constraint plugins:
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint
Symfony constraints:
docroot/vendor/symfony/validator/Constraints
Constraints plugins:
AllowedValues
ComplexData
Count
Email
Null
Length
NotNull
PrimitiveType
Range
Regex
UniqueField
Symfony constraints:
Blank
Callback
CardScheme
Choice
Collection
Count
Country
Currency
Date
EqualTo
File
GreaterThan
Image
Url
etc...
/**
* Email constraint.
*
* Overrides the symfony constraint to use the strict setting.
*
* @Constraint(
* id = "Email",
* label = @Translation("Email", context = "Validation")
* )
*/
class EmailConstraint extends Email {
public $strict = TRUE;
/**
* {@inheritdoc}
*/
public function validatedBy() {
return 'SymfonyComponentValidatorConstraintsEmailValidator';
}
}
Constraints usage example
$definition = DataDefinition::create('string');
$definition->addConstraint('Regex', '/^([0-9]{4}-){3}[0-9]{4}/');
$credit_card = Drupal::typedDataManager()->create($definition);
$credit_card->setValue('yg65-g67dlkj8-9879'); // Invalid value.
$validation1 = $credit_card->validate();
$credit_card->setValue('1250-5154-6548-6848'); // Valid value.
$validation2 = $credit_card->validate();
List data types represent data that is an ordered list of typed data, all of
the same type.
More precisely, the plugins in the list must have the same base plugin ID;
however, some types (for example field items and entities) are provided
by plugin derivatives and the sub IDs can be different.
List Data types
ListInterface methods
getDataDefinition()
isEmpty()
getItemDefinition()
get($index)
set($index, $value)
first()
appendItem($value = NULL)
removeItem($index)
filter($callback)
List data example
$data = [
'1250-5154-6548-6831',
'2233-5154-6648-6843',
'3276-5154-6748-6822',
'4289-5154-6848-6867',
];
$list_definition = ListDataDefinition::create('string');
$credit_cards = Drupal::typedDataManager()->create($list_definition);
$credit_cards->setValue($data);
$validation = $credit_cards->validate();
$first_card = $credit_cards->get(0)->getValue();
foreach ($credit_cards as $card) {
$test[] = $card->getValue();
}
Complex Data
Complex data types, with interface
DrupalCoreTypedDataComplexDataInterface, represent data with
named properties.
The properties can be accessed with get() and set() methods. The value
of each property is itself a typed data object, which can be primitive,
complex, or list data.
The "map" data type
The "map" data type represent a simple complex data type, e.g. for
representing associative arrays. It can also serve as base class for any
complex data type.
By default there is no metadata for contained properties. Extending
classes may want to override
MapDataDefinition::getPropertyDefinitions() to define it.
Defining data types
Create a Definition class that implements one of the Typed Data
interfaces.
Create a DataType plugin that use your Definition class .
To do that, put it in namespace
DrupalyourmodulePluginDataType, and add annotation of type
DrupalCoreTypedDataAnnotationDataType to the
documentation header.
<?php
namespace Drupalactivenet_syncTypedDataDefinition;
use DrupalCoreTypedDataComplexDataDefinitionBase;
use DrupalCoreTypedDataDataDefinition;
/**
* ActiveNet Asset Price definition.
*/
class AssetPriceDefinition extends ComplexDataDefinitionBase {
/**
* {@inheritdoc}
*/
public function getPropertyDefinitions() {
if (!isset($this->propertyDefinitions)) {
$info = &$this->propertyDefinitions;
$info['priceType'] = DataDefinition::create('string')->setRequired(TRUE)->setLabel('priceType');
$info['priceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('priceAmt');
$info['maxPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('maxPriceAmt');
$info['minPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('minPriceAmt');
}
return $this->propertyDefinitions;
}
}
activenet_sync/src/TypedData/Definition/AssetPriceDefinition.php
<?php
namespace Drupalactivenet_syncPluginDataType;
use DrupalCoreTypedDataPluginDataTypeMap;
/**
* Asset Price type.
*
* @DataType(
* id = "asset_price",
* label = @Translation("Asset price"),
* definition_class = "Drupalactivenet_syncTypedDataDefinitionAssetPriceDefinition"
* )
*/
class AssetPrice extends Map {}
activenet_sync/src/Plugin/DataType/AssetPrice.php
$data = [
'priceType' => 'test',
'priceAmt' => 100,
'maxPriceAmt' => 120,
'minPriceAmt' => 100,
];
$price_definition = AssetPriceDefinition::create('asset_price');
$price = Drupal::typedDataManager()->create($price_definition);
$price->setValue($data);
$validation = $price->validate();
$min = $price->get('minPriceAmt')->getValue();
Using data types
In the Field API, data types can be
used as the class in the property
definition of the field.
Describe data defined elsewhere i.e.
schemas from external systems.
In configuration schema files, you can
use the unique ID ('id' annotation)
from any DataType plugin class as the
'type' value for an entry.
paragraphs.paragraphs_type.*:
type: config_entity
label: 'Paragraphs type config'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
YMCA Seattle
Typed Data Explorer
Simple module to browse Typed Data.
https://github.com/wellnet/typed_data_explorer
Links
https://api.drupal.org/api/drupal/core%21core.api.php/group/typed_data/8.2.x
https://www.drupal.org/node/1794140
https://www.sitepoint.com/drupal-8-entity-validation-and-typed-data-explained/
https://www.sitepoint.com/drupal-8-entity-validation-and-typed-data-demonstration/
https://www.youtube.com/watch?v=P49GOFQhKlQ
http://lussoluca.github.io/DDD-2016 - slides from the above video
https://www.youtube.com/watch?v=v7m6qOxH1t0
http://softpixel.com/~mradcliffe/files/dcatl2015-typeddata.pdf - slides from the above
video
https://www.drupal.org/project/xero
Thanks for your attention!

Mais conteúdo relacionado

Mais procurados

Introdução ao ASP .NET Web API
Introdução ao ASP .NET Web APIIntrodução ao ASP .NET Web API
Introdução ao ASP .NET Web APIVinicius Mussak
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introductionSimon Funk
 
Aula1 - Apresentação de Banco de Dados
Aula1 - Apresentação de Banco de DadosAula1 - Apresentação de Banco de Dados
Aula1 - Apresentação de Banco de DadosRafael Albani
 
13 Java Script - Validação de formulário
13 Java Script  - Validação de formulário13 Java Script  - Validação de formulário
13 Java Script - Validação de formulárioCentro Paula Souza
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataLhouceine OUHAMZA
 
What Is Virtual DOM In React JS.pptx
What Is Virtual DOM In React JS.pptxWhat Is Virtual DOM In React JS.pptx
What Is Virtual DOM In React JS.pptxAkrati Rawat
 
Introdução ao desenvolvimento da web.pptx
Introdução ao desenvolvimento da web.pptxIntrodução ao desenvolvimento da web.pptx
Introdução ao desenvolvimento da web.pptxMarceloRosenbrock1
 
Projects In Laravel : Learn Laravel Building 10 Projects
Projects In Laravel : Learn Laravel Building 10 ProjectsProjects In Laravel : Learn Laravel Building 10 Projects
Projects In Laravel : Learn Laravel Building 10 ProjectsSam Dias
 
01 php - introdução ao php
01   php - introdução ao php01   php - introdução ao php
01 php - introdução ao phpRoney Sousa
 
Apostila de Banco dados
Apostila de Banco dadosApostila de Banco dados
Apostila de Banco dadosFernando Palma
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
 
Lecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptxLecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptxSaziaRahman
 

Mais procurados (20)

Introdução ao ASP .NET Web API
Introdução ao ASP .NET Web APIIntrodução ao ASP .NET Web API
Introdução ao ASP .NET Web API
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Aula1 - Apresentação de Banco de Dados
Aula1 - Apresentação de Banco de DadosAula1 - Apresentação de Banco de Dados
Aula1 - Apresentação de Banco de Dados
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
13 Java Script - Validação de formulário
13 Java Script  - Validação de formulário13 Java Script  - Validação de formulário
13 Java Script - Validação de formulário
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
 
What Is Virtual DOM In React JS.pptx
What Is Virtual DOM In React JS.pptxWhat Is Virtual DOM In React JS.pptx
What Is Virtual DOM In React JS.pptx
 
Swagger
SwaggerSwagger
Swagger
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
1. flutter introduccion v2
1.  flutter introduccion v21.  flutter introduccion v2
1. flutter introduccion v2
 
Introdução ao desenvolvimento da web.pptx
Introdução ao desenvolvimento da web.pptxIntrodução ao desenvolvimento da web.pptx
Introdução ao desenvolvimento da web.pptx
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Projects In Laravel : Learn Laravel Building 10 Projects
Projects In Laravel : Learn Laravel Building 10 ProjectsProjects In Laravel : Learn Laravel Building 10 Projects
Projects In Laravel : Learn Laravel Building 10 Projects
 
TypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptxTypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptx
 
06 - Servidor Apache
06 - Servidor Apache06 - Servidor Apache
06 - Servidor Apache
 
Introdução ao LaTeX
Introdução ao LaTeXIntrodução ao LaTeX
Introdução ao LaTeX
 
01 php - introdução ao php
01   php - introdução ao php01   php - introdução ao php
01 php - introdução ao php
 
Apostila de Banco dados
Apostila de Banco dadosApostila de Banco dados
Apostila de Banco dados
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
Lecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptxLecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptx
 

Semelhante a Typed data in drupal 8

Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Tomas Petricek
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt Tasnadi
 
Introduction to Data Science With R Notes
Introduction to Data Science With R NotesIntroduction to Data Science With R Notes
Introduction to Data Science With R NotesLakshmiSarvani6
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)eddiejaoude
 
Boost Your Development With Proper API Design
Boost Your Development With Proper API DesignBoost Your Development With Proper API Design
Boost Your Development With Proper API DesignMarcusHeld1
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxfacebookrecovery1
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastoreHaris Khan
 
Migrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate moduleMigrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate moduleJohan Gant
 
Lesson 2 data preprocessing
Lesson 2   data preprocessingLesson 2   data preprocessing
Lesson 2 data preprocessingAbdurRazzaqe1
 
Data Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonData Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonMOHITKUMAR1379
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardJAX London
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInVitaly Gordon
 

Semelhante a Typed data in drupal 8 (20)

Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
WPF and Databases
WPF and DatabasesWPF and Databases
WPF and Databases
 
Introduction to Data Science With R Notes
Introduction to Data Science With R NotesIntroduction to Data Science With R Notes
Introduction to Data Science With R Notes
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)
 
Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
 
Boost Your Development With Proper API Design
Boost Your Development With Proper API DesignBoost Your Development With Proper API Design
Boost Your Development With Proper API Design
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
 
Migrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate moduleMigrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate module
 
Lesson 2 data preprocessing
Lesson 2   data preprocessingLesson 2   data preprocessing
Lesson 2 data preprocessing
 
Data Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonData Wrangling and Visualization Using Python
Data Wrangling and Visualization Using Python
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedIn
 

Último

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Último (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Typed data in drupal 8

  • 1. Typed Data in Drupal 8 Drupal Cafe Kiev - 22.12.16
  • 2. hello! I am Igor Karpilenko Drupal developer from Deweb studio https://www.drupal.org/u/hamrant https://www.facebook.com/hamrant https://www.linkedin.com/in/hamrant
  • 4. The problem PHP is a very loosely typed language. It doesn’t have a clear definition of the different types of data it deals with. Therefore Drupal used to be the same. For example, there was no consistent way of telling if a field value is a string, an integer or a timestamp.
  • 5. Typed Data The Typed Data API was created to provide developers with a consistent way of interacting with data in different ways. Not only does the API allow you to interact with the actual data, it also provides means of fetching more information, or metadata, about the actual data.
  • 6. The Typed Data API is a low level, generic and reusable object oriented API that appears at multiple levels of the Drupal 8 architecture. Take for example, the EntityAdapter, which extends TypedData and acts as a wrapper for an Entity. Or FieldItemBase, which is an unwrapped extension of TypedData.
  • 7. Each data type in the Typed Data API is a plugin class (annotation class example: DrupalCoreTypedDataAnnotationDataType). These plugins are managed by the typed_data_manager service (by default DrupalCoreTypedDataTypedDataManager). Each data object encapsulates a single piece of data, provides access to the metadata, and provides validation capability.
  • 9. The Typed Data API interfaces List Data Primitive Data Complex Data
  • 10. Primitive Data Implementations of this interface are used for something that represents a single piece of typed data, like a string or integer. This is the smallest building block in the Typed Data API.
  • 11. BinaryData BooleanData Email FloatData IntegerData StringData DateTimeIso8601 - DateTimeInterface DurationIso8601 - DurationInterface TimeSpan - DurationInterface Timestamp - DateTimeInterface Primitive data types
  • 12. PrimitiveInterface methods getValue() - Gets the primitive data value setValue($value) - Sets the primitive data value getCastedValue() - Gets the primitive data value casted to the correct PHP type
  • 13. Primitive data type example /** * The integer data type. * * The plain value of an integer is a regular PHP integer. For setting the value * any PHP variable that casts to an integer may be passed. * * @DataType( * id = "integer", * label = @Translation("Integer") * ) */ class IntegerData extends PrimitiveBase implements IntegerInterface /** * {@inheritdoc} */ public function getCastedValue() { return (int) $this->value; } }
  • 14. create a typed data object in code First get the typed_data_manager service from the container or by calling Drupal::typedDataManager(). Then pass the plugin ID to $manager::createDataDefinition() to create an appropriate data definition object. Then pass the data definition object and the value of the data to $manager::create() to create a typed data object.
  • 15. $definition = DataDefinition::create('integer'); $int = Drupal::typedDataManager()->create($definition); $int->setValue('10'); $validation = $int->validate(); $raw_data = $int->getValue(); $int_data = $int->getCastedValue(); $raw_data_type = gettype($raw_data); $int_data_type = gettype($int_data); Integer data type usage example
  • 16.
  • 17. Constraints The Data Definition class can set constraints upon the Typed Data object. Constraint plugins: core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint Symfony constraints: docroot/vendor/symfony/validator/Constraints
  • 19. /** * Email constraint. * * Overrides the symfony constraint to use the strict setting. * * @Constraint( * id = "Email", * label = @Translation("Email", context = "Validation") * ) */ class EmailConstraint extends Email { public $strict = TRUE; /** * {@inheritdoc} */ public function validatedBy() { return 'SymfonyComponentValidatorConstraintsEmailValidator'; } }
  • 20. Constraints usage example $definition = DataDefinition::create('string'); $definition->addConstraint('Regex', '/^([0-9]{4}-){3}[0-9]{4}/'); $credit_card = Drupal::typedDataManager()->create($definition); $credit_card->setValue('yg65-g67dlkj8-9879'); // Invalid value. $validation1 = $credit_card->validate(); $credit_card->setValue('1250-5154-6548-6848'); // Valid value. $validation2 = $credit_card->validate();
  • 21.
  • 22. List data types represent data that is an ordered list of typed data, all of the same type. More precisely, the plugins in the list must have the same base plugin ID; however, some types (for example field items and entities) are provided by plugin derivatives and the sub IDs can be different. List Data types
  • 24. List data example $data = [ '1250-5154-6548-6831', '2233-5154-6648-6843', '3276-5154-6748-6822', '4289-5154-6848-6867', ]; $list_definition = ListDataDefinition::create('string'); $credit_cards = Drupal::typedDataManager()->create($list_definition); $credit_cards->setValue($data); $validation = $credit_cards->validate(); $first_card = $credit_cards->get(0)->getValue(); foreach ($credit_cards as $card) { $test[] = $card->getValue(); }
  • 25.
  • 26. Complex Data Complex data types, with interface DrupalCoreTypedDataComplexDataInterface, represent data with named properties. The properties can be accessed with get() and set() methods. The value of each property is itself a typed data object, which can be primitive, complex, or list data.
  • 27. The "map" data type The "map" data type represent a simple complex data type, e.g. for representing associative arrays. It can also serve as base class for any complex data type. By default there is no metadata for contained properties. Extending classes may want to override MapDataDefinition::getPropertyDefinitions() to define it.
  • 28. Defining data types Create a Definition class that implements one of the Typed Data interfaces. Create a DataType plugin that use your Definition class . To do that, put it in namespace DrupalyourmodulePluginDataType, and add annotation of type DrupalCoreTypedDataAnnotationDataType to the documentation header.
  • 29. <?php namespace Drupalactivenet_syncTypedDataDefinition; use DrupalCoreTypedDataComplexDataDefinitionBase; use DrupalCoreTypedDataDataDefinition; /** * ActiveNet Asset Price definition. */ class AssetPriceDefinition extends ComplexDataDefinitionBase { /** * {@inheritdoc} */ public function getPropertyDefinitions() { if (!isset($this->propertyDefinitions)) { $info = &$this->propertyDefinitions; $info['priceType'] = DataDefinition::create('string')->setRequired(TRUE)->setLabel('priceType'); $info['priceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('priceAmt'); $info['maxPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('maxPriceAmt'); $info['minPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('minPriceAmt'); } return $this->propertyDefinitions; } } activenet_sync/src/TypedData/Definition/AssetPriceDefinition.php
  • 30. <?php namespace Drupalactivenet_syncPluginDataType; use DrupalCoreTypedDataPluginDataTypeMap; /** * Asset Price type. * * @DataType( * id = "asset_price", * label = @Translation("Asset price"), * definition_class = "Drupalactivenet_syncTypedDataDefinitionAssetPriceDefinition" * ) */ class AssetPrice extends Map {} activenet_sync/src/Plugin/DataType/AssetPrice.php
  • 31. $data = [ 'priceType' => 'test', 'priceAmt' => 100, 'maxPriceAmt' => 120, 'minPriceAmt' => 100, ]; $price_definition = AssetPriceDefinition::create('asset_price'); $price = Drupal::typedDataManager()->create($price_definition); $price->setValue($data); $validation = $price->validate(); $min = $price->get('minPriceAmt')->getValue();
  • 32.
  • 33. Using data types In the Field API, data types can be used as the class in the property definition of the field. Describe data defined elsewhere i.e. schemas from external systems. In configuration schema files, you can use the unique ID ('id' annotation) from any DataType plugin class as the 'type' value for an entry. paragraphs.paragraphs_type.*: type: config_entity label: 'Paragraphs type config' mapping: id: type: string label: 'ID' label: type: label label: 'Label'
  • 35. Typed Data Explorer Simple module to browse Typed Data. https://github.com/wellnet/typed_data_explorer
  • 37. Thanks for your attention!